JAck28 JAck28 - 3 months ago 12
C# Question

Call method based on type

I have combined two types (Type1 and Type2) into one list, by creating an interface they both inherit from.

List<IMyinterface> allElementsList = new List<IMyinterface>();


I now would like to loop through allElementsList, and depending on the Type (Type1 or Type2), do something.

I have set up my code like this:

public interface IMyInterface
{
void DoSomething();
}

public class Type1 : IMyinterface
{
void DoSomething();
}
public class Type2 : IMyinterface
{
void DoSomething();
}


I thought I could just do something like this, and it would call the correct DoSomthing() method depending on the type.

foreach(var i in allElementsList)
{
DoSomething();
}


The above loop is not calling the correct method. How can I call the correct method based on type?

Answer
foreach(var i in allElementsList)
{
    i.DoSomething();
}
Comments