MikeTWebb
MikeTWebb

Reputation: 9279

Identifying the class of an object in a C# IList

I have an IList variable which contains 1 - N entries of myObject. Each entry can be an instance of myObject or any of it's child objects (derived class objects). When doing a foreach over the IList, how can I identify which type of object each member of the IList is?

foreach(myObject anObject in myList)
{
   if(anObject is of type ???)
}

Upvotes: 0

Views: 126

Answers (5)

Joe Enos
Joe Enos

Reputation: 40393

If your OO structure is designed properly, you really shouldn't need to know - whatever you want to do with the object can be done using the appropriate implementation, regardless of which type it is.

With that said, you can get the type of any object by calling:

Type type = myObject.GetType();

And you can compare that type to another specific type, like:

if (myObject.GetType() == typeof(Foo))

The is operator can get you in trouble, depending on your scenario, since it will be true if you are checking if something is a parent class, even if it really is a child. For example:

class Foo {}
class Bar : Foo {}

if (myObject is Foo)

This if will return true for either Foo or Bar objects.

Upvotes: 0

Florian Greinacher
Florian Greinacher

Reputation: 14784

If you want to ask for the type of each instance do it like this:

foreach(myObject anObject in myList)
{
    Type anObjectType = anObject.GetType();
    // Perform appropriate work.
}

Upvotes: 0

user623990
user623990

Reputation:

I'm not much of a .NET developer but in Java there's an operator called instanceof that will check if the object is an instance of a certain class.

Check this link out, it has to do with the typeid of an object, I think that's what you're looking for mate.

http://msdn.microsoft.com/en-us/library/b2ay8610(vs.71).aspx

Upvotes: 0

Can Gencer
Can Gencer

Reputation: 8885

Take a look at the is operator.

foreach(MyObject anObject in myList)
{
   if(anObject is MyTypeWhichInheritsFromMyObject)
     ...
}

Upvotes: 1

WorldIsRound
WorldIsRound

Reputation: 1554

You could make use of

anObject is MyObject

or

Type.IsSubclassOf(MyObject)

You can also make use of baseType.IsAssignableFrom(type) to determine if a type can be derived from a given base type

Upvotes: 1

Related Questions