I would like to make the return type of my method an interface rather than a class for similar reasons stated in c# List or IList, however I am having trouble figuring out how to initialize the interface to return it. I cannot use new IA()
and (IA) new A()
does not work as I cannot cast the result to B
.
interface IA{}
class A: IA{}
class B: IA{}
class UseIA
{
public IA DesiredMethod()
{
return ???;// new IA()
}
public A UndesiredMethod()
{
return new A();
}
}
1
An implementation of an interface is the realization of that interface. Realization is being implemented within the class. Just return an instance of the class (A or B) which realizes the return-type interface.
interface IA{}
class A: IA{}
class UseIA
{
public IA DesiredMethod()
{
return new A();
}
}
4
The point of declaring an interface as the return type is not to actually return something with only an interface type. You can’t, since interfaces can’t be instantiated. The point is to make the contract of your method more explicit: “I’m returning something with a doA()
method, but not necessarily a classic StandardA
object. I might be switching to a SecretSuperDuperA
object some day, and you wouldn’t know the difference. All you know is that whatever I return will have the doA()
method you need.”
In other words, it allows the implementation writer more latitude how to do the job of the method best, while still ensuring that the caller actually gets the specific bit of functionality that they need.
Just a small expansion on @Kaan’s post. This is to point out polymorphism, since the O.P. has two classes implementing one interface.
interface IA { }
class A : IA { }
class B : IA { }
class UseIA
{
public IA DesiredMethod()
{
return new A; // let's say, for the purposes of the exercise, that class A is the default implementation of IA
}
public IA DesiredMethod(String whichImplementationOfIA) // overloaded method
{
switch (whichImplementationOfIA)
{
case "GiveMeA": return new A();
case "GiveMeB": return new B();
default:
throw new ArgumentException(); // or, alternatively, return A, because it's a default implementation in this exercise
}
}
}
By the way, the second scenario (where an argument specifies which class will be created) is reminiscent of Class Factory patterns.