Piotrek
Piotrek

Reputation: 1416

How can class implement interface with one property also implement other interface

Sorry for no clear title, It seems like common problem, but I can't find anything. I need to create class that implements interface like below, but why I get this error? Is there something missing, or it isn't possible to do things like that?

    public class Car : ICar
    {
        public Wheel Wheel { get; set; } //this makes relation in db
    }

    public interface ICar
    {
        IWheel Wheel { get; set; }
    }

    public class Wheel : IWheel
    {

    }

    public interface IWheel
    {

    }

Error:

'Car' does not implement interface member 'ICar.Wheel'. 'Car.Wheel' cannot implement 'ICar.Wheel' because it does not have the matching return type of 'IWheel'.

Upvotes: 1

Views: 132

Answers (1)

O. R. Mapper
O. R. Mapper

Reputation: 20732

Implement the property from the interface explicitly:

public class Car : ICar
{
    public Wheel Wheel { get; set; }

    IWheel ICar.Wheel
    {
        get { return Wheel; }
        set { Wheel = (Wheel)value; }
    }
}

That way, users of your class will see the "original" Wheel property typed to the full-fledged Wheel class, whereas whoever uses the interface will get the explicit implementation (that, in your case, quite directly maps to the other property, but is, in any case, considered separate by the compiler).

Note the cast in the setter and its implications, in case the interface really needs to have a writeable property.

Upvotes: 2

Related Questions