Nicolas Charette-Naud
Nicolas Charette-Naud

Reputation: 144

How to get the type of a generic parameter by reflection

I need to get the generic type of an generic parameter by reflection. But the real type, and not the type { Name="T" ; FullName=null }

public void Sample<T>(T i, object o)
{
    MethodBase basee = MethodBase.GetCurrentMethod();
    Type[] types = basee.GetGenericArguments();
}

but i can't use typeof(T), because i'm using reflection

Is there a way (using reflection) to get type type of generic arguments.

// in this case i should get (Type) { Name="Int32" ; FullName="System.Int32" }
myClassObj.Sample(10, new object());

In other therm, i whant to know how to call the method called by typeof(T) ex:

// in Il code I see that the compiler use:
// ldtoken !!T => this should get the RuntimeTypeHandle needed as parameter
// System.Type::GetTypeFromHandle(valuetype System.RuntimeTypeHandle)
Type t = Type.GetTypeFromHandle( ? ? ? ); 

How could i get the RuntimTypeHandle from a T generic arguments

Upvotes: 1

Views: 695

Answers (1)

Mike Zboray
Mike Zboray

Reputation: 40838

I don't know the point of all this, but what about

public void Sample<T>(T i, object o)
{
  Type t = typeof(T);
  if (i != null)
  {
    t = i.GetType();
  }

  // Do whatever with t
  Console.WriteLine(t);
}

Then you've got the run time type (if there is an object), otherwise you've got the static type.

Upvotes: 4

Related Questions