picrap
picrap

Reputation: 1254

In a .NET generic method, how to get the actual parameters type

In a generic method, I want to know the type of the actual parameters passed. For example I have two classes:

class A {}
class B {}

Then a method taking any class as argument:

void M<T>(T instance)
{
    // how to tell what is the type of T if instance is null?
    // (so instance.GetType() won't work)
}

For example how to make a difference between the two following calls in the invoked method:

M<A>(null);
M<B>(null);

Is such a thing possible? The method MethodBase.GetCurrentMethod() returns the generic method definition, not the actual generic arguments. Same thing for StackTrace frames.

Upvotes: 0

Views: 59

Answers (1)

Grax32
Grax32

Reputation: 4059

typeof(T) gets you the type. Usually when I am in a generic class or method, this is the type that I want to base something on.

instance.GetType() gets the type of the instance but I may be looking for an implemented interface or a base class and .GetType() will never return that. Also, as you pointed out, if you call .GetType() on a null, you will get a null reference exception.

Upvotes: 1

Related Questions