'Can I define a method of interface type inside a class

abstract class someClass
{
    public abstract IProduct SomeMethod();
}

public interface IProduct
{
    string Operation();
}

I have seen the above code having a method define inside abstract class with type interface, I wonder the use of this. Can anybody explain?



Solution 1:[1]

You are asking about this:

abstract class SomeBaseClass
{
    public abstract IProduct SomeMethod();
}

In this case, IProduct may represent any object that implements the interface, and the method SomeMethod() is guaranteed to return an object of some class implementing IProduct.

This has many uses where the design dictates that all classes that derive from SomeBaseClass be able to create objects that adhere to the IProduct interface.

In interfaces are like contracts that guarantee specific behavior and properties.

This means that regardless of the actual implementation, code like this below is valid

SomeBaseClass f = ...
IProduct p = f.SomeMethod();
string op = p.Operation();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1