Why would someone ever do:
const object useless = null;
const IEnumerable meaningless = null;
Eric Lippert says features are unimplemented by default and every possibility adds more effort in testing, maintaining etc... Why would a null value for a reference type ever needed as a constant?
Servy's point is a good one. Let me explain that point in a slightly different way.
Let's start by asking the more general question "should the C# 1.0 compiler classify a null literal of reference type as a constant?" I want to emphasize that we are reasoning about C# 1.0 here, so any concerns about nullable value types or generics are not on your mind.
Well, what's the point of classifying anything as a constant? The point is that there are certain language constructs that require constants:
case
clauseAnd constants have an effect on reachability analysis:
Now, let's suppose that we accept that
null
is useful in attributes andcase null
and that though it is a bit weird,ought to be treated as the constant true. Your proposal then is to say that
null
is a constant in these three ways, but nevertheless cannot be assigned to aconst
local or field??? That is a bizarre restriction; ifnull
may be treated like a constant in every other situation where a constant is required, then why should it not be treated as a constant when defining a field or local?But of course I haven't answered your actual question, which is "when is this useful?"
Well, again, let's push back. When is any constant useful? Constants are treated by the compiler as though their value is substituted into their usage, so why would you ever say:
when you could simply say
? When I put it like that I hope the reasoning is obvious. The reason you use any constant field or local is to give a name to a value so that the reader of the code understands it better. A null constant field or local is exactly the same. It is arguably more clear to read:
than