Home >Backend Development >C++ >C# Null Checks: When to Use `x is null` vs. `x == null`?
Null Reference Comparisons in C#: "x is null" vs. "x == null"
In C# 7, the introduction of the pattern matching operator is has raised questions about its usage compared to the traditional == null expression. While these expressions may seem interchangeable when dealing with null, there are key differences to consider when comparing reference types.
Type Consideration
Unlike == null, which compares object references for equality, x is null checks for the type of x. If x is a reference type, x is null returns true only if x is null. In contrast, x == null returns true for both null and reference types with values other than null.
class Foo {} Foo foo = null; Console.WriteLine(foo is null); // True Console.WriteLine(foo == null); // True
Performance Implications
Internaly, x is null calls System.Object.Equals(object, object), while x == null calls ceq (a comparison method for reference types). For null references, both expressions have the same performance since they both return true. However, for non-null references, x is null can be significantly slower due to its additional type checking.
Overloaded Equality Operators
When an equality operator (such as == or Equals) is overloaded for a specific type, x is null no longer checks for type equality and instead delegates to the overloaded operator. On the other hand, x == null always checks for reference equality.
class Foo { public static bool operator ==(Foo left, Foo right) => ... public static bool operator !=(Foo left, Foo right) => ... } Foo foo1 = new Foo(); Foo foo2 = null; Console.WriteLine(foo1 is null); // False (checks type only) Console.WriteLine(foo1 == null); // False (delegates to overloaded operator) Console.WriteLine(foo2 is null); // True (checks type only) Console.WriteLine(foo2 == null); // True (reference comparison)
When to Use One over the Other
In general:
Ultimately, the choice between x is null and x == null depends on the specific requirements of your code.
The above is the detailed content of C# Null Checks: When to Use `x is null` vs. `x == null`?. For more information, please follow other related articles on the PHP Chinese website!