What is default(object) used for?
I was asked what the meaning of default(object) is in the following piece of code:
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:
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.
Comments
I try to apply "Don't make me think", "Try to lead to the pit of success", and "Prefer explicit over implicit" principles, all of which result in the better code constructs to be (object) null and (int?) null to be preferred over _default(object) and _default(int?), etc.
Reading the default({type name}) statement requires extra mental processing to stop reading and determine the default value of the type, and then mentally replace the assignment your eyes see with the value you determined and then begin reading again. Reading the ({type name) null statement requires no extra mental machinations or comprehension blips because the type and the value are explicit.
The default(int?) statement could unintentionally be typed with the question mark omitted, resulting in default(int) which would happily compile and be a hard bug to track down visually. The (int) null statement won't even compile. Any good static analysis tool will have that bug red lined in your IDE before you even get to writing the next line of code.
C#'s
default
is the equivalent to VB'sNothing
.Ed, I'm in agreement with you on the reasoning, and for that reason I think that the
default(object)
is the more readable of these terms.Comment preview