Is String NULL always equal to another String NULL in C#?

  • A+
Category:Languages

On my VS 2015 compiler, I tested that

    static void Main(string[] args)     {         string str1 = null;         string str2 = null;         if(str1==str2)  //they are the same on my machine         {         }     } 

But this is a documented behavior? NULL by definition, is an undefined behavior, so comparing NULL to another NULL could be undefined. It could happen that on my machine, using my current .Net framework, the two NULLs turn out to be the same. But in the future, they could be no longer the same.

In that case, my code will break silently.

Is it safe to always assume that the above two NULL strings are always the same?

 


Yes, that's documented here

If both a and b are null, the method returns true.

and this method is used when you use ==, which is mentioned here.

calls the static Equals(String, String) method

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: