Should I avoid using the C# "is" operator for equality checks?

Viewed 191

A colleague told me I could use is and is not instead of the equality operators == and !=. I thought the is operator had something to do with types, and the official docs on MSDN agrees, but it also states:

Beginning with C# 7.0, you can also use the is operator to match an expression against a pattern

I didn't think checking values with is would work, but strangely it does:

> "tomato" is "apple"
false
> 1 is not 2
true

I assume it is the "expression pattern matching" at work here(?). My question is, since using is as the equality operator (==) seemingly works for values as well, is there any reason to avoid it? Would it be fine, performance and readability wise, to use is for all equality checks?

1 Answers

With the exception of x is null they are the same and a matter of taste for constant values. As in described in the comments, pattern matching only works for constants. The special case of checking for null guarantees to not use any overloaded equality operator. I cross-checked that with ILSpy:

Original source code:

string tomatoString = "tomato";
object tomatoObj = "tomato";
Console.WriteLine(tomatoString.Equals("tomato"));
Console.WriteLine(tomatoString is "tomato");
Console.WriteLine(tomatoObj is "tomato");
Console.WriteLine("tomato" is "tomato");
Console.WriteLine(tomatoString is null);

Decompiled with ILSpy:

string tomatoString = "tomato";
object tomatoObj = "tomato";
Console.WriteLine(tomatoString.Equals("tomato"));
Console.WriteLine(tomatoString == "tomato");
string text = tomatoObj as string;
Console.WriteLine(text != null && text == "tomato");
Console.WriteLine(value: true);
Console.WriteLine(tomatoString == null);

(For Completness: Note that if you test it with literals on both sides, the compiler will just replace it with its constant result. Note that the static type will introduce necessary null checks)

Related