Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

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?

like image 971
Graviton Avatar asked Jul 31 '18 08:07

Graviton


People also ask

Can a string equal null?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.

IS null same as empty string in C?

The value null represents the absence of any object, while the empty string is an object of type String with zero characters. If you try to compare the two, they are not the same.

How do you check if a string is equal to null?

You can use the IsNullOrWhiteSpace method to test whether a string is null , its value is String. Empty, or it consists only of white-space characters.

IS null equal?

equals(null) will always be false. The program uses the equals() method to compare an object with null . This comparison will always return false, since the object is not null . (If the object is null , the program will throw a NullPointerException ).


2 Answers

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

like image 155
Tim Schmelter Avatar answered Oct 13 '22 12:10

Tim Schmelter


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.

like image 39
Safwan Shaikh Avatar answered Oct 13 '22 10:10

Safwan Shaikh