C# - Using subclasses to implement interfaces

Viewed 75

I have the following interfaces

    public interface IPrice
    {
        int Price { get; }
    }

    public interface IGear : IPrice
    {
        GearUpgrade Upgrades { get; }
    }

and the following classes

    public class GearUpgrade : IPrice
    {
        public int Price
        {
            get { return price; }
            set { price = value; }

        }
    }

    public class ArmorUpgrade : GearUpgrade
    {
    }

    public class ShieldUpgrade : GearUpgrade
    {
    }

    public class WeaponUpgrade : GearUpgrade
    {
    }

So when I try to implement an IGear like this...

    public class Armor : IGear
    {
        private int price = 0;
        public int Price { get => price; }

        private ArmorUpgrade upgrades;
        public ArmorUpgrade Upgrades
        {
            get { return upgrades; }
            set { upgrades = value; }
        }

    }

I get the following error:

'Armor' does not implement interface member 'IGear.Upgrades'. 'Armor.Upgrades' cannot implement 'IGear.Upgrades' because it does not have the matching return type of 'GearUpgrade'.

I figured that if Upgrades is from a subclass of GearUpgrade, the interface should be fulfilled, but apparently it is not... Did I make a false assumption?

1 Answers

In order to implement the interface, the method signatures have to match exactly: C# doesn't apply covariance and contravariance implicitly.

Here's a simple fix to allow Armor to implement the IGear interface without messing with the class:

public class Armor : IGear
{
    private int price = 0;
    public int Price { get => price; }

    private ArmorUpgrade upgrades;
    public ArmorUpgrade Upgrades
    {
        get { return upgrades; }
        set { upgrades = value; }
    }

    GearUpgrade IGear.Upgrades => this.Upgrades;
}
Related