Bazinga
Bazinga

Reputation: 1014

How do I determine the List<Object>'s object?

I am looking to create a generic method that receives a List. I need to determine what the object is within the list so that I can then do the necessary work according to the object that is being passed in within the list. How can I determine the kind of object that the List contains?

Upvotes: 1

Views: 97

Answers (3)

Panos Rontogiannis
Panos Rontogiannis

Reputation: 4172

If the object type is not one of the generic parameters of your method then you can use the Type.GetGenericArguments method that returns the types of the parameters of a generic type (in your case List).

Else if the object type is one of the generic parameters of your method then use Travis J's answer.

Upvotes: 1

Travis J
Travis J

Reputation: 82277

given

List<T> objects;

you can get the type like this

var objType = typeof(T);

Upvotes: 1

well you have the is keyword, which can compare objects

if(myObject is MyClass)
    doStuff();

you also have

typeof(myObject);

and as L.B. said, you have

obj.GetType() too

Upvotes: 2

Related Questions