Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

How to get the type of T from a member of a generic class or method?

Let state I have a generic member in a class or method, so:

public class Foo<T>
{
public List<T> Bar { get; set; }

public void Baz()
{
// get type of T
}
}


At the point when I start up the class, the T becomes MyTypeObject1, so the class has a generic list property: List<MyTypeObject1>. The equivalent applies to a generic strategy in a non-generic class:
public class Foo
{
public void Bar<T>()
{
var baz = new List<T>();

// get type of T
}
}


I might want to know, what type of objects the listed of my group contains. So the listed property called Bar or the local variable baz, contains what sort of T?

I can't do Bar[0].GetType(), because the list might contain zero elements. How might I do it?
by

3 Answers

sandhya6gczb
To get the type of T from the member of a generic class or method use

Type typeParameterType = typeof(T);
RoliMishra
With the following extension method you can get away without reflection:

public static Type GetListType<T>(this List<T> _)
{
return typeof(T);
}


Or more general:

public static Type GetEnumeratedType<T>(this IEnumerable<T> _)
{
return typeof(T);
}


Usage:

List<string>        list    = new List<string> { "a", "b", "c" };
IEnumerable<string> strings = list;
IEnumerable<object> objects = list;

Type listType = list.GetListType(); // string
Type stringsType = strings.GetEnumeratedType(); // string
Type objectsType = objects.GetEnumeratedType(); // BEWARE: object
pankajshivnani123
If you don't need the whole Type variable and just want to check the type you can easily create a temp variable and use is operator.

T checkType = default(T);

if (checkType is MyClass)
{}

Login / Signup to Answer the Question.