Question

This might have been asked already. I'v searched SO and found a few questions on Null VS String.Empty, but I am curious as why the following statement does not throw a NullReferenceException:

String value = null;

if (value != "x") { // does not throw Exception here

    String test = value.Trim(); // throw Exception here as expected

}
Was it helpful?

Solution

Equality and Inequality operators are overloaded for strings.So when you do this:

value != "x"

It calls System.String::op_Inequality which calls the String.Equals method:

public static bool operator != (String a, String b) 
{
    return !String.Equals(a, b);
}

And String.Equals is implemented like this:

public static bool Equals(String a, String b)
{
    if ((Object)a == (Object)b)
    {
        return true;
    }

    if ((Object)a == null || (Object)b == null)
    {
        return false;
    }
    if (a.Length != b.Length)
            return false;

    return EqualsHelper(a, b);
}

As you can see, it casts the strings to object and returns false if one of them is equal to null.I assume you confused about why comparing string doesn't return null because they are compared by values instead references therefore I share some details.But generally comparing a null object with something never throws a NullReferenceException.That exception is only thrown if you try to call a method on a null object.

OTHER TIPS

Why it should throw Exception?

it throws Exception when you are trying to perform any operation means invoking any memebers of that variable value.

if (value != "x")

basically here you are just comparing its value(null) with x which does not throw any exception.

Because in this case you are testing if null and "x" are different and this is a valid operation (the result is true obviously).

In the second step you try to call a method on an undefined object, so the exception is raised.

Compare your code with:

if (value != null)
{
    ...
}

This obviously works for value being either null or non-null ("x", say). The comparison in this latter case becomes

if ("x" != null)

or equivalently

if (null != "x")

which is equivalent to your original test of

if (value != "x")

where value is null.

It's fine to compare null and non-null values (always false, of course). You can't, however, call a method on a null object as in your example.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top