You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#With the new ability to write x is null in C# 7, I anticipate questions on whether this is preferable/equivalent to x == null as we role out C# 7 at my workplace.
Looking at the generated IL code, it seems that x == null generally does a better job since x is null always calls Object.Equals(a, b). This seems especially costly for Nullable<T>, since in that case we get a boxing operation. Interestingly, the null pattern in switch statements does not seem to have this issue.
For the sake of simplicity, it would be nice if x is null had the exact same performance as x == null and case null:, avoiding a (very minor) performance gotcha.
Version Used: C# 7 (via LinqPad)
Steps to Reproduce:
I wrote the following C# code and compiled in LinqPad with optimization on:
public class Program
{
public static void Main(string[] args) { }
public bool IsNullA(int? a)
{
switch (a)
{
case null: return true;
default: return false;
}
}
public bool IsNullB(int? a)
{
return a is null;
}
public bool IsNullC(object s)
{
switch (s)
{
case null: return true;
default: return false;
}
}
public bool IsNullD(object s)
{
return s is null;
}
}
@madelson Thank you for the comprehensive report with the descriptive IL blocks. I'm closing this as a duplicate, but know that it's still very much appreciated to now have this extra information available. 👍
sharwell
added
Community
The pull request was submitted by a contributor who is not a Microsoft employee.
Resolution-Duplicate
The described behavior is tracked in another issue
and removed
Community
The pull request was submitted by a contributor who is not a Microsoft employee.
labels
May 26, 2017
#With the new ability to write
x is null
in C# 7, I anticipate questions on whether this is preferable/equivalent tox == null
as we role out C# 7 at my workplace.Looking at the generated IL code, it seems that
x == null
generally does a better job sincex is null
always callsObject.Equals(a, b)
. This seems especially costly forNullable<T>
, since in that case we get a boxing operation. Interestingly, the null pattern in switch statements does not seem to have this issue.For the sake of simplicity, it would be nice if
x is null
had the exact same performance asx == null
andcase null:
, avoiding a (very minor) performance gotcha.Version Used: C# 7 (via LinqPad)
Steps to Reproduce:
Expected Behavior:
IsNullA
should use aHasValue
call for the null check andIsNullD
should use a branch instruction.Actual Behavior:
IsNullA
andIsNullD
both useObject.Equals(a, b)
.The text was updated successfully, but these errors were encountered: