CS1720 warning, erroneously (?), Generated for an extension method

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 will be as expected:

String is null
String is null

      

But the C # compiler gives CS1720 warning for the first tagged line:

warning CS1720: expression always throws a System.NullReferenceException because the default for 'string' is null

My question is: Why did the compiler assume there would be a NullReferenceException? The first call is Extension()

equivalent to the second, but the second does not raise a warning. Both calls must be safe because this string str

- is a parameter that can be safe, as shown in the second line. I was able to reproduce this on 3.5, 4.0 and 4.5 compilers, but not Mono 3.0.7.

+3


source to share


2 answers


Obviously, the answer is yes, the warning is wrong. You've proven it well enough. (This may be why this warning)



As discussed earlier , this does not harm the invocation of an extension method with a value null

. I think the compiler team didn't go through all the problems to check if a method can call it an extension method or not.

+3


source


In the first case, you remove the reference to the null object, in the second case, you call the method with a null argument.

== update ==



Let me reformulate, yes, that doesn't seem like a legitimate warning. I suspect that the compiler is throwing a warning because it thinks it is "bad" to eliminate the null object. The warning is probably preceding the extension function.

It would be interesting to see how Roslyn breaks it.

+1


source







All Articles