tags:

views:

109

answers:

2

I have some code that works like the below. I was wondering if its possible to get a Type object for the generic type passed to the DoSomething function. I realise that T is a type parameter but how would i turn this into a type object. The dosomething function is in a class where I want to know the underlying type used by the list object.

[STAThread]
static void Main(string[] args)
{
    List<string> stringList = new List<string>();
    DoSomething(stringList); 
}
public void DoSomething<T>(List<T> collection)
{
    //Type myType = T; ??!!? 
    //do something here with the list.
}

Many thanks

Will

+11  A: 

Just use:

Type type = typeof(T);

Generic parameters are like any other type except you don't know what exactly that type is at compile time, so it is assumed it is the uppermost in the object hierarchy which fits the type constraints given (for no constraints its System.Object).

Wim Hollebrandse
Thought i'd add info on what exactly a generic type is, hope you don't mind!
RCIX
I don't think it needed that, as the OP seems well aware of what a generic type is. ;-) But fine with me mate.
Wim Hollebrandse
A: 

Sorry not sure how to say this was the right answer but this is! Thanks, cant believe I didnt try it, thanks for your help

wdhough
Please don’t post a separate answer to say thanks. Post a comment on the answer instead.
Timwi