9

I have:

public class MyUserControl : WebUserControlBase <MyDocumentType>{...}

How do I get the TypeName of MyDocumentType if I'm in another class?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Karlo Medallo
  • 672
  • 7
  • 17
  • http://stackoverflow.com/questions/557340/c-sharp-generic-list-t-how-to-get-the-type-of-t – Nahum Mar 20 '13 at 09:44

4 Answers4

7

You can use something like this:

typeof(MyUserControl).BaseType.GetGenericArguments()[0]
Daniel Hilgarth
  • 171,043
  • 40
  • 335
  • 443
3

There are plenty answers showing how to get the type of T if you know that the class derives directly from WebUserControlBase<T>. Here's how to do it if you want to be able to go up the hierarchy until you encounter the WebUserControlBase<T>:

var t = typeof(MyUserControl);
while (!t.IsGenericType
    || t.GetGenericTypeDefinition() != typeof(WebUserControlBase<>))
{
    t = t.BaseType;
}

And then go on to get T by reflecting on the generic type arguments of t.

Since this is an example and not production code, I 'm not handling the case where t represents a type that does not derive from WebUserControlBase<T> at all.

Jon
  • 428,835
  • 81
  • 738
  • 806
1

If you are on .NET 4.5:

typeof(MyUserControl).BaseType.GenericTypeArguments.First();
cuongle
  • 74,024
  • 28
  • 151
  • 206
  • 3
    This is good, but one should keep in mind that the `GenericTypeArguments` property only exists starting from .NET 4.5. – Jon Mar 20 '13 at 09:50
1

You can use Type.GetGenericArguments method.

Returns an array of Type objects that represent the type arguments of a generic type or the type parameters of a generic type definition.

Like

typeof(MyUserControl).BaseType.GetGenericArguments()[0]

Since return type of this method is System.Type[], the array elements are returned in the order in which they appear in the list of type arguments for the generic type.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364