views:

64

answers:

3

How do you get the name of a generic class using reflection

eg

public class SomeGenericClass<T>
{
}

SomeGenericClass<int> test = new SomeGenericClass<int>();

test.GetType().Name returns "SomeGenericClass'1"

How do I get it to return "SomeGenericClass" without the '1?

A: 

How about just the following?

test.GetType().Name.Split('\'')[0]

It works on non-generic classes too.

Noldorin
This would work but I was wondering if I could access the property directly?
Petras
Why doesn't it get the actual type of `SomeGenericClass<int>`?
Robert Harvey
Down-vote because?
Noldorin
@Petras: As neilwhitaker1 points out, the `'1` is actually part of the name (and refers to one generic type parameter). As far as the CLR is concerned, there is no typ called `SomeGenericClass`, but only one called `SomeGenericClass'1` - someone correct me if I'm wrong here.
Noldorin
+4  A: 

The '1 is part of the name, because, for example, List<T> and List (if I created such a class) are different classes.

'1 means that it has one type parameter. If you want to know the type of that parameter, use test.GetType().GetGenericArguments()[0];

Neil Whitaker
+1  A: 
enum.GetName(test.GetType(), test).ToString()