What is the difference between “is not null” and “!= null”?

The main difference between e != null and e is not null is the way the the compiler executes the comparison.

Microsoft: “The compiler guarantees that no user-overloaded equality operator == is invoked when expression x is null is evaluated.”

Bottom Line: If you are writing code that you don’t want to depend on someone’s implementation of the != and == operators, use is null and is not null because it is safer.

See the following example:

public class TestObject
{
  public string Test { get; set; }

  // attempt to allow TestObject to be testable against a string
  public static bool operator ==(TestObject a, object b)
  {
    if(b == null)
      return false;
    
    if(b is string)
      return a.Test == (string)b;

    if(b is TestObject)
      return a.Test == ((TestObject)b).Test;

    return false;
  }

  public static bool operator !=(TestObject a, object b)
  {
    if(b == null)
      return false;
    
    if(b is string)
      return a.Test != (string)b;

    if(b is TestObject)
      return a.Test != ((TestObject)b).Test;

    return false;
  }
}

If you have code that needs to ensure that an object isn’t null, using is not null will give you better results with TestObject than using != null because the overload of the ==/!= operators is a little odd.

Console example 1:

TestObject e = null;

if(e == null)
  Console.WriteLine("e == null");

if(e is null)
  Console.WriteLine("e is null");

Output: e is null

Console example 2:

TestObject e = new TestObject();

if(e != null)
  Console.WriteLine("e != null");

if(e is not null)
  Console.WriteLine("e is not null");

Output: e is not null

Neither overloaded operator is implemented “correctly” so the Console never outputs e == null or e != null.

Leave a Comment