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 NULL
s 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?
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.
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.
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.
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 ).
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With