Reputation: 1385
I have 3 classes:
class O
{
}
class A : O
{
}
class B : A
{
}
When I call my code:
List<O> myList = new List<O>();
myList.Add(new A());
myList.Add(new B());
foreach (O obj in myList)
{
if (obj is A)
{
// do something
}
else if (obj is B)
{
//do something
}
}
However I realized that if (obj is A)
will be evaluated to be true
even when my obj
is of class B
. Is there a way to write the statement such that it evaluates to true if and only if obj
is of class B
?
Upvotes: 0
Views: 52
Reputation: 57202
Why don't you define a virtual function in the base class and override it in the derived types, doing what you need in the different cases?
class O {
public virtual void DoSomething() {
// do smtgh in the 'O' case
}
}
class A : O {
public override void DoSomething() {
// do smtgh in the 'A' case
}
}
class B : A {
public override void DoSomething() {
// do smtgh in the 'B' case
}
}
Then your loop becomes
foreach (O obj in myList) {
obj.DoSomething();
}
Upvotes: 3
Reputation: 25352
There are two method GetType
and typeof
GetType is a method on object. It provides a Type object, one that indicates the most derived type of the object instance.
and
Typeof returns Type objects. It is often used as a parameter or as a variable or field. The typeof operator is part of an expression that acquires the Type pointer for a class or value type
Try like this
if(obj.GetType() == typeof(A)) // do something
else if(obj.GetType() == typeof(B)) //do something
Upvotes: 0