How to Nullable <T> use a base extension type method
An hour ago, I asked a question: how to write an extension method for Enum?-Nullable<Enum>
surprisingly, I got an answer saying that I can write an extension method for Enum and it can be used for all enumerations and numbered enums.
Cool, it works , but how?
If I understand correctly, all the enumerations come from Enum , so I can use this extension method in every enum that I have.
But ... an enumeration of ItemType? , for example, is not an enumeration, it is Nullable<ItemType> , which is not the result of ItemType and Enum .
Just like List<DataReader> does not derive from DataReader and therefore cannot use DataReader methods, although DataReader is a generic type.
I know that the Nullable<T> has a lot of voodoo and syntactic sugar, is this one of them?
Extension methods do not require a class to be / retrieved, they simply require that a transformation exist (more precisely: an implicit identity, a reference or a box transformation, this is §7.6.5.2 "Invoking an extension method").
The conversion from Nullable<ItemType> to System.Enum is a conversion to boxing; same as conversion from Nullable<int> to System.Object .
And if you define your own struct Test : IMyInterface {} structure, the conversion will happen from Nullable<Test> to IMyInterface .
Box conversions from nullables return a null reference if nullable is null; otherwise, enter a value of zero. See §6.1.7 “Conversion Boxing” in the C # Specification for more details.
This is more system magic than compiler magic. Since Enum is a reference type, this means that any value you pass will receive a box (for example, converted to a link).
Now Nullable<T> has special processing in the CLR that in the box it will give wither null if it represents a null value or a value in an internal type ( T ) box, but never fits in a Nullable<T> box, of course the opposite. unboxing to a null type accepts a null reference.
The extension method is converted to a static method, for which the first argument is the variable on which the method was called.
In the Enum example, since Enum is a class (not a structure), then the extension method can accept either a specific enumeration value (which usually comes down to int) or null. therefore it works with null enumerations.
the same won't work for int? (Nullable). if you create an extension method for int, you cannot call it on Nullable (it will tell you: "it is not possible to convert the argument type of the Nullable instance to int)