One hour ago I asked a question: how can I write an extension method for Enum?-Nullable<Enum>
surprisingly I got an answer telling me I can write the extension method for Enum and it can be used for all enums and nullable enums.
Cool, it workes, but how?
If I understand correctly, all enums derive from Enum so this why I can use this extension method in every enum I have.
But… the ItemType? enum, for example, isn’t an enum, it’s Nullable<ItemType>, which doesn’t derives from ItemType nor Enum.
Just like List<DataReader> doesn’t derive from DataReader and thus can’t use DataReader methods, though DataReader is it’s Generic type.
I know The Nullable<T> type has a lot of “voodoo” and syntactic sugar, is this one of them?
Extension methods do not require the class to be /derived/, they just require a conversion to exist (more specifically: an implicit identity, reference or boxing conversion; this is §7.6.5.2 “Extension method invocations”).
The conversion from
Nullable<ItemType>toSystem.Enumis a boxing conversion; same as a conversion fromNullable<int>toSystem.Object.And if you defined your own structure
struct Test : IMyInterface {}, there would be a conversion fromNullable<Test>toIMyInterface.Boxing conversions from nullables will return a null reference if the nullable was null; and box the nullable’s value otherwise. For details see §6.1.7 “Boxing conversions” in the C# specification.