Can somebody explain me the need in C# language for typeof(SomeGenericType<>), with no concrete parameters specified.
I put together the following example:
var t1 = typeof(Nullable<>);
var t2 = typeof(Nullable<int>);
var q = 1 as int?;
var b1 = t1.IsInstanceOfType(q); //false
var b2 = t2.IsInstanceOfType(q); //true
I first thought typeof(Nullable<>) is “more generic” than t2, which specifies generic parameter int, but b1 turns out to be false – so instance of int? is not instance of Nullable<>.
So how a variable should be defined for b1 to be true? what practical uses does it have?
It can’t. (In fact, with
Nullable<T>you’ll run into interesting boxing problems anyway, but there we go…)At execution time, values are always instances of closed types.
Nullable<>,List<>are open generic types. It’s never useful to callIsInstanceOfTypeon such a type. That doesn’t mean it’s useless though.Typically open types are used in reflection. For example:
There can be code high up which is generic, but calls into lower levels passing in
Typevalues instead – the list could then go back up the stack and be cast toIEnumerable<T>for the appropriate value ofT.Likewise you may want to create a closed type with reflection to call a method on it, etc.
You can also use it to find out whether a particular type implements a generic interface for some type argument – for each interface implemented, you can find out if it’s generic, get the generic type definition, and see whether that’s equal to (say)
IEnumerable<>.