The documentation of constant pattern matching with the is
-operator (expr is constant
) states:
The constant expression is evaluated as follows:
If
expr
andconstant
are integral types, the C# equality operator determines whether the expression returnstrue
(that is, whetherexpr == constant
).Otherwise, the value of the expression is determined by a call to the static
Object.Equals(expr, constant)
method.
Therefore, when using this code
public bool IsZero(int value)
{
return value is 0;
}
I expect it to use the ==
operator (case 1) and generate this code:
.method public hidebysig instance bool
IsZero(
int32 'value'
) cil managed
{
.maxstack 8
ldarg.1
ldc.i4.0
ceq
ret
}
However, in reality, the integer parameter and the constant (literal) are boxed in order to be passed to the static Object.Equals
method (case 2):
.method public hidebysig instance bool
IsZero(
int32 'value'
) cil managed
{
.maxstack 8
ldc.i4.0
box [mscorlib]System.Int32
ldarg.1
box [mscorlib]System.Int32
call bool [mscorlib]System.Object::Equals(object, object)
ret
}
Why is that the case?
IsZero
method? – Gabrila4.6.1
to4
it boxes the value. – Gabrila4.7.2
with VS17... and it still boxes. – Canellac#
versions too). I believe that's because of new Pattern Matching feature, which apparently checking value type's type without boxing. – Gabrila