While performing code review, I found code that could cut down on potential bugs by using the Null object pattern. Then I began thinking: wouldn’t it be useful if the default value of that business object was a null object instead of a null reference?
Since C# provides the default operator, I tried to overload it like this:
public static MyObject operator default (MyObject object)
{
return MyObject.Null;
}
That gives me the error: ‘Overloadable unary operator expected’. On further digging, I found that one part of the docs says that default(T) is a Primary operator:Overloadable Operators.
And when you actually click on default(T) on the above page, it says default is a keyword.
On top of that, this page doesn’t say that default is not overloadable: Overloadable Operators (C# Programming Guide).
I know this is kind of academic but I am trying to understand the language deeper. What is default(T)? Is it an operator or a keyword? And why is not overloadable (from a language design standpoint)?
UPDATE: Yes I’ve read C# language spec section 7.5.13 and I know what the language does. I am trying to understand why.
Overloading
defaultwould complicate the design of C# and the runtime significantly. Currently it is assumed that the binary zeroing of any value type is valid and equivalent todefaultof that value type. And for references thenullreference is always valid and equivalent todefaultof any reference type.This allows the runtime to start running the constructors on an objects in a binary zero state and get sane behavior.