Does Null Check Perform on a General Boxing Case?

I looked around and could not find an answer. Let's say I have this code:

class Command<T> : ICommand<T> { public void Execute(T parameter) { var isNull = parameter == null; // ... } } 

T can be any class, even a Nullable<> . Does the check above perform a box reason if T is a value type? I understand that this is the same as calling ReferenceEquals , which takes two object arguments from which a box can arise if T was a value type, if I understood correctly.

If the above action causes boxing, is there a preferable way to do this without causing a window to appear? I know that there is default(T) , but in the case of int , that is 0 , and I look to see if this value is null without its box. Also, I am looking to do this in a way that satisfies both the values ​​and the reference types.

+6
source share
1 answer

No - at least not in my understanding. If T is the type of a non- parameter == null value, the parameter == null check is effectively replaced with false JIT compiler; verification of execution is not performed.

This is an optimization that only a JIT compiler can do, since the C # compiler generates only one form of code. For example, IL generated for your sample:

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

This will apparently actually do the boxing, but I trust a decent JIT compiler to determine that when T not null, ceq always gives a false result and removes the box operation.

+4
source

All Articles