Search code examples
c#stringvisual-studio-2015null-conditional-operator

Why can I apply a null-conditional operator to a hardcoded string?


I have a bool variable like this:

bool myBool = true;

If I write if (myBool == null) I get the following warning:

The result of the expression is always 'false' since a value of type 'bool' is never equal to 'null' of type 'bool?'.

That's clear to me because it doesn't make sense to check whether a non-nullable variable is null. Visual Studio notices that and marks as warning.

Now I have a string, which is nullable by default, as I know.

Why can I apply a null-conditional operator to a hardcoded string without Visual Studio noticing it? I'm thinking of something like this:

"This is a string"?.AnyStringMethod();

Shouldn't Visual Studio notice that this string isn't null at all?


Solution

  • Visual Studio must go off the type that the operator is working with.

    When you create a bool, there is no way that it could ever be null by the type, until you change that type to bool?.

    However, with a hard coded string, even though it has text within the quotes, there's no guarantee that it will stay there. The "variable" that gets created (even as just a plain string) is still of type string, which is able to have a null assigned to it and not change the type.

    What you are looking for would be for them to inspect the value of every variable that they are creating. If they were to do that, then why not also check for something like this?

    var i = 0;
    
    if (i > 2) // This will always be false!
    

    Update

    As InBetween mentioned in the comments, there is a bit of an oversight in here as well. Having a string such as "Some string" that is not assigned in a variable is functionally equivalent to const string s = "Some string";. If you were to declare it like that, the code inspectors will detect if you run a comparison on that, such as the following:

    const string s = "Some String";
    if (s == null) // This will give a warning that this can't happen
    

    I would attribute that difference in the way that the const is handled versus the way a plain static string is handled could be attributed to different development teams working on different parts at different times. Again, this is such an edge case that doesn't cause huge problems that it doesn't get warned that no one working on it most likely didn't think about it.