Given
int foo = 1;
Type unboundType = typeof(List<>);
Type w = unboundType.MakeGenericType(typeof(int));
if (w == typeof(List<int>))
{
Console.WriteLine("Yes its a List<int>");
try
{
((List<int>)(object)w).Add(foo);
}
catch(InvalidCastException)
{
Console.WriteLine("No you can't cast Type");
}
}
I can verify that the type indeed matches a constructed type and perform an action based on said constructed type. However, I cannot cast Type to it’s class using as or an explicit cast. Is there a practical purpose for allowing developers to create a Type of unbound type or does this functionality exist solely to support the language in some way?
Not everything can be done at compile time. Sometimes, particularly in library code, you need to take what you are given. In scenarios where you are given just an
objector aTypeand need to do some clever processing, unbound types can be really helpful; for example:Basically; scenarios that use a lot of reflection or meta-programming will probably find themselves using unbound types at some point.