When is null not null?

In JavaScript, that's when. Say you have an object in C# like Person with string properties for FirstName and LastName. Something like this:

public class Person
    public string FirstName { get; set; }
    public string LastName { get; set }

Those properties are, of course, nullable.  In JavaScript, an instance of that object might look something like this:


That's what the JSON symbol would look like. Now if you wanted to set the FirstName to null and pass that object back to some controller on the server-side code, you might expect something like this:


Well, we came across this today. We passed the above JSON through the MVC.net ModelBinder and this is what came out on the server-side:

+ FirstName = "null"
+ LastName = "Yon"

Wait, what!?! A little digging reveals that <em>null</em> in JavaScript is a special object with type of object. Somehow the default ModelBinder interprets that to be a string and infers that we really wanted "null" instead of null. What we wanted, in fact, was undefined instead. That is a special value whose type is "undefined." So passing this JSON


will achieve the desired effect. It's a simple concept and a subtle difference but a potential gotcha, nonetheless.