How to change return type of a method in an implementation of an interface?

  • Thread starter Thread starter Jarmo Muukka
  • Start date Start date
J

Jarmo Muukka

Hello,

I have an interface which has a method which returns an interface. I would
like to return a real type in implemented class.

interface IFoo
{
....
}

interface ISomething
{
IFoo Method();
}

class Foo : IFoo
{
....
}

class Something : ISomething
{
IFoo Method()
{
return new Foo();
}
}

I would like to return Foo as a return type of Method. Is it possible?

Microsoft has done it, but how? They have a SqlDataReader class which
implements IDataReader and they have a SqlCommand which implements
IDbCommand. IDbCommand has a method ExecuteReader which returns IDataReader,
but ExecuteReader of SqlCommand returns SqlDataReader. How did they do this?

JMu
 
It is called an "explicit interface implementation", and you can do it like
this.

interface IInterface
{
IAnotherInterface Whatever ( ) ;
}

class AnotherInterfaceImplementor
: IAnotherInterface
{
....
}

class Implementor
: IInterface
{

public AnotherInterfaceImplementor Whatever ( )
{
return new AnotherInterfaceImplementor();
}

IAnotherInterface IInterface.Whatever ( )
{
return Whatever();
}


}
 
You need to use explicit interface implementation. Try the following:

public interface IFoo

{

}

public interface ISomething

{

IFoo Method();

}

public class Foo: IFoo

{}

public class Something: ISomething

{

IFoo ISomething.Method()

{

return this.Method();

}

public Foo Method()

{

return new Foo();

}

}



Hope that helps.

- Markus
 
Back
Top