Home > Mobile >  Implement an interface consuming and returning the same interface in C#
Implement an interface consuming and returning the same interface in C#

Time:02-01

I am having trouble implementing an interface with C#:

    public interface IFooable
    {
        public (IFooable left, IFooable right) FooWith(IFooable other);
    }

And then in my concrete class, I have

class Concrete
{
        public (Concrete left, Concrete right) FooWith(Concrete other)
        {
            return GoFooSomewhereElse(...);
        }
}

But in my tests, the compiler tells me that Concrete does not implement the FooWith function.

I don't really understand what is going on, since I am so new at C# and easily confused by the language!

I found similar questions (eg Why can't I override my interface methods?) but they did not solve my problem.

CodePudding user response:

According to Liskov Substitution Principle, a superclass object should be replaceable with a subclass object without breaking the functionality of the software.

Your Concrete class apparently doesn't implement the interface, because if I try to pass the argument of some AnotherFooable class to FooWith() method it will not work.

Instead you could make it generic:

public interface IFooable<T>
{
    public (T left, T right) FooWith(T other);
}

class Concrete : IFooable<Concrete>
{
    public (Concrete left, Concrete right) FooWith(Concrete other)
    {
        return GoFooSomewhereElse(...);
    }
}

Also you can put the restriction to the generic type argument, if you want FooWith() method to accept only arguments of the same class (as in your example, where you have Concrete.FooWith(Concrete, Concrete)):

public interface IFooable<T> where T : IFooable<T>
...

CodePudding user response:

Try this trick with generic:

public interface IFooable<T>
{
    public (T left, T right) FooWith(T other);
}

class Concrete : IFooable<Concrete>
{
    public (Concrete left, Concrete right) FooWith(Concrete other)
    {
        return GoFooSomewhereElse(...);
    }
}

CodePudding user response:

Here's an example of how you could implement an interface in C# that consumes and returns the same interface:

public interface IMyInterface
{
    IMyInterface DoSomething(IMyInterface input);
}

public class MyClass : IMyInterface
{
    public IMyInterface DoSomething(IMyInterface input)
    {
        // Implementation goes here
        return input;
    }
}

Please refer the link for Detail Explanation :

https://salesforce-devloper.blogspot.com/2023/02/implement-interface-consuming-and.html

  • Related