Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Performing a Null Check on a Generic Cause Boxing? [duplicate]

Tags:

c#

.net

boxing

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.

like image 565
Mike-E Avatar asked Feb 08 '18 12:02

Mike-E


1 Answers

No - at least not in my understanding. If T is a non-nullable value type, the parameter == null check is effectively replaced with false 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:

IL_0000:  ldarg.1
IL_0001:  box        !T
IL_0006:  ldnull
IL_0007:  ceq

That would appear to actually perform the boxing - but I trust a decent JIT compiler to spot that when T is non-nullable, the ceq will always give a false result, and remove the box operation.

like image 90
Jon Skeet Avatar answered Nov 20 '22 01:11

Jon Skeet