Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Inheritance question

Status
Not open for further replies.

cpastre

Programmer
Nov 13, 2002
10
US
I'm having trouble trying to "override" a method from an inherited interface but return a different data type than is defined by the interface. Here's an example to clarify:

public interface IDataReader {}

public interface IDbCommand
{
IDataReader ExecuteReader();
}

public class MyCommand : IDbCommand
{
public IDataReader ExecuteReader() {return new MyDataReader();} }

public class MyDataReader : IDataReader {}

class Test
{
static void Main(string[] args)
{
MyCommand cmd = new MyCommand();
MyDataReader dr = cmd.ExecuteReader();
}
}

When I compile this I get "Cannot implicitly convert type 'IDataReader' to 'MyDataReader'" at the "MyDataReader dr = ..." line. I use the IDbCommand/IDataReader as an example because I've seen it in the SqlClient. The SqlClient analog to "MyDataReader dr = ...," "SqlDataReader dr = ..." does not produce the same error when compiled. So my question is, how do I modify my code to avoid having to explicitly cast "cmd.ExecuteReader()" to MyDataReader?

Thanks,
Charlie

Charlie Pastre
Transition/1 MAS
cpastre@t1mas.com
 
Update: Got the solution to this one from another newsgroup:

-----Original Message-----
Sent: Wednesday, November 20, 2002 3:10 PM
To: DOTNET-CX@DISCUSS.DEVELOP.COM
Subject: Re: [DOTNET-CX]

You can work around this to some extent with explicit interface
implementation. For example:

public class MyCommand : IDbCommand
{
IDataReader IDBCommand.ExecuteReader()
{return ExecuteReader();}
public MyDataReader ExecuteReader()
{return new MyDataReader(); }
}

--Peter Golde
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top