Reputation: 387
I have a class as follows:
class Object
{
...
Method();
}
And a number of classes which inherit it:
class ObjectVariant1 : Object
{
...
Method1();
}
class ObjectVariant2 : Object
{
...
Method2();
}
I have a list, into which all objects are put:
List<Object> objectList = new List<Object>();
I want to be able to go through the list and for each member I want to be able to call the MethodX() within the variant class rather than the inherited Method().
The only way I have found to do this is as follows:
foreach (var obj in objectList)
{
if (obj is ObjectVariant1)
{
ObjectVariant1 newObj = (ObjectVariant1)obj;
newObj.Method();
}
if (obj is ObjectVariant2)
{
ObjectVariant2 newObj = (ObjectVariant2)obj;
newObj.Method();
}
}
However I would like to be able to add new ObjectVariant classes easily, without having to add extra checks like these. Is there a way to automate the foreach loop without me having to add a new check for each class that I create?
Thanks!
Upvotes: 0
Views: 194
Reputation: 13676
You could change Object
to interface IObject
and use it:
public interface IObject
{
void Method();
}
class ObjectVariant1 : IObject
{
public void Method()
{
}
}
class ObjectVariant2 : IObject
{
public void Method()
{
}
}
And then you could use your List<IObject> objectList
and call obj.Method()
Another way of doing it (using polymorphism in C#) is by using virtual
- override
keywords
Upvotes: 1