Reputation: 14419
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).
Upvotes: 2
Views: 451
Reputation: 8206
Shouldn't
public void MySpecialMethod(List<MyObject> objects)
{
foreach (ISomethingElse o in objects)
o.B();
}
work?
Upvotes: 1
Reputation: 61437
Personally, I would use the following signature as IEnumerable<T>
is covariant:
public void MySpecialMethod(this IEnumerable<ISomething> objects) // <- the problem
{
foreach (ISomething o in objects)
o.A();
}
Calling it:
objects.MySpecialMethod();
Upvotes: 4
Reputation: 81660
List does not support covariance.
You may change it to IEnumerable<ISomething>
and pass a List<MyObject>
.
Upvotes: 4
Reputation: 4833
You can use IEnumerable<>
interface instead of List<>
. IEnumerable<>
is covariant.
Upvotes: 5