Piotr
Piotr

Reputation: 11

Overriding a method with a derived class instance as argument

I have a base class, Item, in which I have an abstract method, OnItemEquipped, that takes an Item and performs operations on that Item that are common to all Items.

The intention is that I will have several derived classes, such as Item_Consumable, whcih will override the abstract method from the base class. The problem is, I want this new method to take Item_Consumable as an argument, rather than an Item. This is a problem, since the compiler will complain about the signature of the method not matching. But in my derived implementation I want to use the fields that are unique to Item_Consumable - otherwise I would just have implemented the whole method inside my base class and not bothered with overriding at all.

What is the accepted strategy for this kind of problem?

Functionally, my code looks like this:

public class Item
{

    public virtual void OnItemEquipped(Item item){

    }

}



public class Item_Armour : Item
{
    public float uniqueFloat;

    public override void OnItemEquipped(Item item){
        UseUniqueFloat(uniqueFloat);
    }

}

And the actual error is:

'Item' does not contain a definition for 'protection' and no accessible extension method 'protection' accepting a first argument of type 'Item' could be found (are you missing a using directive or an assembly reference?)

Where 'protection' is my uniqueFloat.

Upvotes: 0

Views: 61

Answers (1)

Anu Viswan
Anu Viswan

Reputation: 18173

You could make use of Generics for the purpose. You should begin by defining interface which could act as the constrain.

public interface IItem
{
}
public abstract class Item<T> where T : IItem
{
    public virtual void OnItemEquipped(T item)
    {
    }
}

public class Item_Armour :Item<Item_Armour>,IItem
{
    public string UniqueFloat{get;set;}
    public override void OnItemEquipped(Item_Armour item)
    {
        UseUniqueFloat(item.UniqueFloat);
    }

    public void UseUniqueFloat(string uniqueFloat)
    {
    }
}

This would ensure that the Derived Classes would be able to use an instance of themselves as the arguement to the overridden method

Demo Code

Upvotes: 1

Related Questions