Posts Tagged ‘ Generics ’

How to create a generic list using reflection

Reflection is a very powerful feature which allows you to do lots of crazy things.
But sometimes you want to create a generic class which can be really annoying if you dont know how to do it.

If you try to do it as usual then you will receive an exception.
An example would be

var myType = typeof (double);
var list = (List<myType>) Activator.CreateInstance(typeof (List<myType>), null);

The compiler tells you that a type or namespace is expected and not myType!

 

In order to do that you can use the MakeGenericType method to add the generic types to the List and after that you can create the instance

var myGenericType = typeof(List<>).MakeGenericType(new []{typeof(double)});
var myList = (List<double>)Activator.CreateInstance(myGenericType);

Note that the MakeGenericType method only creates the type which then is used to create an object in the next line

How to assign null to Generics (T)? The solution is Default(T)!

If you are working with generic methods / classes you may have the problem that you can not assign null to a generic type

which means that the following example results in the compile error (Can not convert expression type ‘null’ to return type ‘T’).

private T Foo<T>()
{
    return null;
}

The reason for this compile error is that T could even be a value type. And value types (int, double, etc.) can not be null.
Maybe you also tried a dirty workaround

private T Foo<T>()
{
    return (T)(object)null;
}

But this results in a NullPointer exception. Because it is more or less the same problem as before.
You assign null to a object and then to T which results in the same problem as before.

When i first faced the problem i was not sure how to solved it.
But Google telled me that there exists the default(T) keyword which solves this problem.

private T Foo<T>()
{
   return default(T);
}

I hope that it helps somebody which is in the same situation as I was 🙂