Home > Net >  C# Interface using a child type class
C# Interface using a child type class

Time:09-02

Let's say I create this interface :

interface Equipable
{
    public bool Equip(Equipment equipment);
}

Let's just assume our Equipment class is empty for now:

class Equipment
{

}

I create a derived class from Equipment (let's keep it simple):

class Trinkets : Equipment
{
    ...
    public Trinkets(...)
    {
        ...
    }
}

Then I want a Trinket class that implements Equipable and that uses its method:

class Trinket : Item, Equipable
{
    bool Equipable.Equip(Trinkets trinkets)
    {
        return true;
    }
}

But it seems I can't do this (CS0539), I can't use Trinkets class (which however is Equipment derived class) as a method parameter of my interface.

This didn't work for me and seems far-fetched: Implementation of interface when using child class of a parent class in method of interface. And it also seems that the above solution does not allow you to use other classes than the base class declared in the interface header.

So my question is simple, is there a way to do what I'm trying to do? Is it bad practice? If it is, what should I do to overcome this problem?

CodePudding user response:

According to your description that you need an interface that accepts a reference to Equipment. In C#, this means it can accept an object of that class or any derived class on method call. This doesn't include the method implementation.

So Trinket should be declared like this:

class Trinket : Item, Equipable
{
    bool Equipable.Equip(Equipment equipment)
    {
        return true;
    }
}

But this allows you to call that method passing it an object of type Equipment or Trinkets as a derived class of Equipment. Here's a simple example on that:

var trs = new Trinkets();
var eq = new Equipment();

var tr = new Trinket();
tr.Equip(trs);

// Or
tr.Equip(eq);

The inheritance will work on object references but not when implementing the method.

CodePudding user response:

On line bool Equipable.Equip(Trinkets trinkets)

You specified in the Equipable interface that all classes that implement Equipable need to contain a defined method called Equip that receive an Equipment parameter and return a bool. The method you defined in the Trinket class receive a Trinket parameter, so it wont satisfy the condition set out by the interface.

  • Related