So I have two interfaces:
public interface ISomething
{
public int A();
}
public interface ISomethingElse
{
public int B();
}
And an object that implements both:
public class MyObject : ISomething, ISomethingElse
{
}
Now I have this running code:
...
List<MyObject> objects = myObjectManager.SelectAll(); // now have say 10 MyObject
MyUtilityClass myUtilityClass = new MyUtilityClass();
MyOtherUtilityClass myOtherUtilityClass = new MyOtherUtilityClass();
myUtilityClass.MySpecialMethod(objects); // <- compile failure
myOtherUtilityClass.MySpecialMethod(objects); // <- another failure
...
If I want to call A or B on all of them, how can I write code like this:
public class MyUtilityClass
{
public void MySpecialMethod(List<ISomething> objects) // <- the problem
{
foreach (ISomething o in objects)
o.A();
}
}
public class MyOtherUtilityClass
{
public void MySpecialMethod(List<ISomethingElse> objects) // <- the problem
{
foreach (ISomethingElse o in objects)
o.B();
}
}
How can I cleanly call MyUtilityClass.MySpecialMethod()
on my List<MyObject> objects
? Is it possible without all typecasting? The parameters of MyUtilityClass.MySpecialMethod()
appear to be the issue (I want to define the parameter as a List of objects that implement ISomething).