Graviton
Graviton

Reputation: 83254

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

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?

Upvotes: 5

Views: 1352

Answers (2)

Safwan Shaikh
Safwan Shaikh

Reputation: 546

If both strings are null, the method always return true because == are used for reference comparison. In simple words, == checks if both objects point to the same memory location.

I tried this example with java str1.Equals(str2) and this returns Null Pointer Exception, because .Equals evaluates to the comparison of values in the objects.

Hope it helps you.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460058

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

Upvotes: 15

Related Questions