What type are you really?

I had an interesting problem the other day. I had a situation where someone could pass a type to my method which could be potentially be a nullable type and I needed to know what the real type actually was.

It turned out to be pretty easy to find out. The Type type has a method called GetGenericTypeDefinition() which will tell you the generic type. Then you can use GetGenericArguments() to return a list of types that the generic type has been instantiated with:

if(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable))
	Type[] genericTypes = type.GetGenericArguments();
	if (genericTypes.Length == 1)
	type= genericTypes[0];

There’s a simple example on the Microsoft site and a really in depth example that has information about a whole lot of other related stuff as well.

Posted on 04 May 07 by Helen Emerson (last updated on 04 May 07).
Filed under .NET