Nitin bhatia
Nitin bhatia

Reputation: 35

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?

Upvotes: 0

Views: 378

Answers (1)

John Alexiou
John Alexiou

Reputation: 29244

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();

Upvotes: 1

Related Questions