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

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
 
D

Dennis Myrén

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


}
 
M

Markus Minichmayr

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top