Consider the following program:
static class Program
{
static void Extension(this string str)
{
if(str == null)
Console.WriteLine("String is null");
else
Console.WriteLine("String is not null");
}
static void Main(string[] args)
{
default(string).Extension(); // <--- warning
Extension(default(string)); // <--- no warning
}
}
The output is as expected:
String is null
String is null
But, the C# compiler gives a CS1720 warning on the first marked line:
warning CS1720: Expression will always cause a System.NullReferenceException because the default value of 'string' is null
My question is: Why would the compiler suggest there will be a NullReferenceException? The first call to Extension()
is equivalent to the second one, but the second does not produce a warning. Both calls ought to be safe because this string str
is a parameter, which can safely be null, as seen in the second line. I have been able to reproduce this on the 3.5, 4.0, and 4.5 compilers, but not Mono 3.0.7.