Is it possible to find object's class in the list of objects?

I've got a list of objects = { obj1,obj2,obj3 }

Every class of the objects is inherited from the same interface

interface IObjects
class Obj1:IObjects
class Obj2:IObjects
class Obj3:IObjects

And I want to find object of Obj1 class for examp. How to do it?

Upvotes: 1

Views: 87

Answers (5)

llama
llama

Reputation: 1651

Call GetType() on your object. see here. Hope this helps

Upvotes: 1

D Stanley
D Stanley

Reputation: 152626

Linq method:

IObjects[] objList = new IObjects[] { obj1,obj2,obj3 };
obj1 o1 = objList.Where(o => o.GetType() = typeof(Obj1)).First();

Upvotes: 1

ntziolis
ntziolis

Reputation: 10231

You can do so by:

var listOfObject1s = objects.Where(o => o is Obj1).ToList();

Upvotes: 4

Michel Keijzers
Michel Keijzers

Reputation: 15367

Iterate through the list and check for

item is Obj1

Upvotes: 1

Moo-Juice
Moo-Juice

Reputation: 38820

if(obj.GetType() == typeof(Obj1))
{
    // obj is an Obj1!
}

Upvotes: 1

Related Questions