With two posts in as many days, you might get the wrong idea. Let me reassure you: you cannot count on me posting regularly.
That being said, I just found another neat C# abuse and had to share.
It’s occasionally useful (or necessary, or both) to use
null as a starting value or to explicitly return a
null value. Aside from initializing a local variable, another (more interesting) example of the former is the
fold for you functional programmers—overload that takes a seed.
In certain circumstances, specifying
null can cause difficulty for the compiler. With the previously referenced method, a
null seed will break generic type inference and force you to either:
nullto the correct type (yuck!) or
- explicitly specify the two type arguments (double yuck!)
null is also required when trying to use
null as a result for the ternary operator (<condition>
: <false-result>). The compiler needs to know (and verify) the type of that expression, and gripes about “no implicit conversion” when it sees a
It turns out there’s another option, though.
When the .NET Framework 2.0 introduced generics, there was a need for a way to express the default value for a generic type (since generic types could be either value or reference types). So the
default keyword (of switch fame) was overloaded with a new function.
What isn’t explicitly mentioned in that documentation is that you can use
default with concrete types, too. And an expression using
default is strongly typed.
So, now instead of saying:
You have the option of saying:
I’m not sure yet if I actually prefer this to typecasting
null. It certainly looks odd, but that could just be unfamiliarity.
But I thought it had potential and wanted to share. Thoughts?