In fact, there is a difference in semantics between the two comparisons. The extreme case appears when you compare null with a type that is overloaded with the == operator.
foo is null will use direct link comparisons to determine the result, while foo == null , of course, will run the overloaded operator == if it exists.
In this example, I introduced an βerrorβ in the overloaded == operator, causing it to always throw an exception if the second argument is null :
void Main() { Foo foo = null; if (foo is null) Console.WriteLine("foo is null");
The IL code for foo is null uses the ceq statement to perform direct link comparisons:
IL_0003: ldloc.0
The IL code for foo == null uses a call to the overloaded statement:
IL_0016: ldloc.0
So the difference is that if you use == you run the risk of running custom code (which could potentially have unexpected behavior or performance issues).
Thorkil Holm-Jacobsen Jun 12 '18 at 7:37 2018-06-12 07:37
source share