3

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.

cmv
  • 956
  • 1
  • 8
  • 13
  • 2
    It is just a bug, [reported here](https://connect.microsoft.com/VisualStudio/feedback/details/695362/c-compiler-gives-incorrect-warning-expression-will-always-cause-a-system-nullreferenceexception-for-extension-methods). They didn't look in a hurry to fix it back then. – Hans Passant Oct 30 '14 at 21:18
  • You could add a `#pragma warning disable 1720` (with a nice comment describing why). – clcto Oct 30 '14 at 21:21

2 Answers2

3

Obviously the answer is yes, the warning is incorrect. You have proven that quite well. (Probably that is the reason it is a warning after all)

As discussed earlier it doesn't harm to call an extension method with a null value. I guess the compiler team didn't get through all the hussle to check whether the method to call it an extension method or not.

Community
  • 1
  • 1
Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
1

In the first case you are de-referencing a null object, in the second case you are calling a method with a null argument.

==update==

Let me re-state, yes this doesn't appear to be a legitimate warning. I suspect the compiler is issuing a warning because it believes that deref'ing a null object is "bad". The warning likely pre-dates the extension method feature.

It would be interesting to see how Roslyn breaks it down.

Dweeberly
  • 4,668
  • 2
  • 22
  • 41