C# – Make Return Type an Interface – Problem with Initialization

cinitializationinterfacesreturn-typetype casting

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

Best Answer

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();
  }
}
Related Topic