I looked around for this and could not find an answer. Say I have this code:
class Command<T> : ICommand<T>
{
public void Execute(T parameter)
{
var isNull = parameter == null;
// ...
}
}
T
could be any class, even a Nullable<>
. Does performing the check above cause boxing if T
is a value type? My understanding is that this is the same as calling ReferenceEquals
which takes two object
arguments, either of which would cause boxing if T
was a value type, if I understand correctly.
If the above does cause boxing, is there a more preferred way to do this without causing the box to occur? I know there is default(T)
but in the case of int
that is 0
, and I am looking to see if this value is null
without boxing it. Also, I am looking to do this in a way that satisfies both value and reference types.
No - at least not in my understanding. If
T
is a non-nullable value type, theparameter == null
check is effectively replaced withfalse
by the JIT compiler; no execution-time check is performed.This is an optimization that only the JIT-compiler can perform, as the C# compiler only generates one form of code. For example, the IL generated for your sample is:
That would appear to actually perform the boxing - but I trust a decent JIT compiler to spot that when
T
is non-nullable, theceq
will always give a false result, and remove the box operation.