Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, Object and multiple Interface implementations: how to use correctly?

Tags:

c#

interface

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).

like image 576
Cymen Avatar asked Jan 26 '26 22:01

Cymen


1 Answers

You can use IEnumerable<> interface instead of List<>. IEnumerable<> is covariant.

like image 169
oxilumin Avatar answered Jan 29 '26 11:01

oxilumin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!