Explicit interface implementation...
Gyorgy Bozoki <[email protected]>
| Newsgroups | gmane.comp.windows.devel.dotnet.advanced |
|---|---|
| Message-ID | <[email protected]> |
Hi all,
I have a question about explicit interface implementations in C#/.Net 2.0.
Consider this example:
//------------
public interface IValueIDPair
{
string Value { get; }
int ID { get; }
}
// Returns objects of type T from a list by index.
public interface IMyIterator<T>
{
int Count { get; }
T Item ( int lIndex );
}
// Returns IValueIDPair objects from a list by index.
public interface IMyInterface : IMyIterator<IValueIDPair>
{
}
// Some list class that can return items either as objects or as
IValueIDPair interfaces.
public class MyClass : IMyInterface
{
public int Count
{
get
{
return ( 10 );
}
}
public object Item ( int lIndex )
{
return ( null );
}
public IValueIDPair IMyInterface.Item ( int lIndex ) // FAILS
{
return ( null );
}
}
//------------
The above code (specifically, the class) fails to compile, because
IMyInterface doesn't have ID and Value members - its base interface has
those members. I must implement IMyInterface explicitly because my class has
two ID and two Value properties.
Is this how C# is defined? The docs don't mention anything about such a
scenario and it seems strange to say the least that the derived interface
cannot be implemented explicitly.
If I change the line marked with FAILS to
public IValueIDPair IMyIterator<IValueIDPair>.Item ( int lIndex )
then it works. This, however seems to defeat the purpose of having the
derived (more specialized) IMyInterface, since I still have to remember that
it's defined as IMyIterator<IValueIDPair>. Also, I want to access this class
through IMyInterface, not through IMyIterator<IValueIDPair>, so having an
explicit implementation for the latter simply breaks my plans (I'll have to
cast the class to the generic interface, not to IMyInterface.)
I know I could rename the Count/Item functions in the IMyIterator interface
so that the new names don't clash, but that seems like a clumsy workaround
for something that the compiler should be able to do right away.
Is there anything I can do to use the derived interface? To me this looks
like a bug in the C# 2.0 compiler, unless the specs say this is how it
should be. (In which case I question the usefulness of the explicit
interface feature.)
Thanks for any advice,
Gyorgy Bozoki
===================================
View archives and manage your subscription(s) at http://peach.ease.lsoft.com/archives