Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface inheritance and the new keyword

Tags:

c#

interface

I want:

public interface IBase
{
    MyObject Property1 { get; set; }
}

public interface IBaseSub<T> : IBase
{
    new T Property1 { get; set; }
}

public class MyClass : IBaseSub<YourObject>
{
    public YourObject Property1 { get; set; }
}

But this doesn't compile. It gives the error:

//This class must implement the interface member IBase.Property1

Can anyone shed some light on this? I thought it should work..

Thanks

like image 777
Chaos Avatar asked Mar 23 '11 02:03

Chaos


1 Answers

IBaseSub<T> requires IBase. I say "requires" because it more accurately reflects the practical implications than to say it "inherits" IBase, which implies overriding and other things that simply don't happen with interfaces. A class which implements IBaseSub<T> can actually be said to implement both, like so:

public class MyClass : IBase, IBaseSub<YourObject>

Going back to what I said about inheritance - there is no such thing with interfaces, which means just because both interfaces have a property with the same name, the derived one isn't overriding or hiding the base one. It means that your class must now literally implement two properties with the same name to fulfill both contracts. You can do this with explicit implementation:

public class MyClass : IBase, IBaseSub<YourObject>
{
    public YourObject Property1 { get; set; }
    MyObject IBase.Property1 { get; set; }
}
like image 159
Rex M Avatar answered Sep 20 '22 03:09

Rex M