What is default(object) used for?

time to read 2 min | 213 words

I was asked what the meaning of default(object) is in the following piece of code:

from e in docs.Events
select new {
Registration = default(object)
}
view raw index.cs hosted with ❤ by GitHub

The code is something that you’ll see a lot in RavenDB indexes, but I understand why it is a strange construct. The default(object) is a way to null. This is asking the C# compiler to add the default value of the object type, which is null.

So why not simply say null there?

Look at the code, we aren’t setting a field here, we are creating an anonymous object. When we set a field to null, the compiler can tell what the type of the field is from the class definition and check that the value is appropriate. You can’t set a null to a Boolean properly, for example.

With anonymous objects, the compiler need to know what the type of the field is, and null doesn’t provide this information. You can use the (object)null construct, which has the same meaning as default(object), but I find the later to be syntactically more pleasant to read.

It may make more sense if you’ll look at the following code snippet:

var user = new
{
AcceptedEula = default(bool?), // set to null, mark the field as bool?
RegisteredAt = DateTime.Today, // set to today, the field is DateTime
Name = default(string), // set to null, mark the field as string
ActiveTasks = 0, // set to 0, the field is an int
};
view raw anonymous.cs hosted with ❤ by GitHub

This technique is probably only useful if you deal with anonymous objects a lot. That is something that you do frequently with RavenDB indexes, which is how I run into this syntax.