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


i have bool variable this:

bool mybool = true; 

if write if (mybool == null) following warning:

the result of expression 'false' since value of type 'bool' never equal 'null' of type 'bool?'.

that's clear me because doesn't make sense check whether non-nullable variable null. visual studio notices , marks warning.

now have string, nullable default, know.

why can apply null-conditional operator hardcoded string without visual studio noticing it? i'm thinking of this:

"this string"?.anystringmethod(); 

shouldn't visual studio notice string isn't null @ all?

visual studio must go off type operator working with.

when create bool, there no way ever null type, until change type bool?.

however, hard coded string, though has text within quotes, there's no guarantee stay there. "variable" gets created (even plain string) still of type string, able have null assigned , not change type.

what looking them inspect value of every variable creating. if that, why not check this?

var = 0;  if (i > 2) // false! 

update

as inbetween mentioned in comments, there bit of oversight in here well. having string such "some string" not assigned in variable functionally equivalent const string s = "some string";. if declare that, code inspectors detect if run comparison on that, such following:

const string s = "some string"; if (s == null) // give warning can't happen 

i attribute difference in way const handled versus way plain static string handled attributed different development teams working on different parts @ different times. again, such edge case doesn't cause huge problems doesn't warned no 1 working on didn't think it.


Comments

Popular posts from this blog

sql - invalid in the select list because it is not contained in either an aggregate function -

Angularjs unit testing - ng-disabled not working when adding text to textarea -

How to start daemon on android by adb -