Ohlafl
Ohlafl

Reputation: 41

How to call subclass method via base class without casting

Given the following classes:

class BaseItem {}

class ItemA : BaseItem {

    public int Calculate() {
        return 0 + 1;
    }
}

class ItemB : BaseItem {
    public int Calculate() {
        return 1+1;
    }
}

... would it be possible in some way to do the following in an external controller class:

BaseClass a = new ItemA();
int result = a.Calculate();

... so that result equals 1 or 2 depending on which subclass is instantiated (i.e. without having to recast any class)? I've done some attempts using interface and override but I'm having difficulties wrapping my head around returning the result variable "upwards". Thanks.

Upvotes: 0

Views: 2119

Answers (2)

jonvw
jonvw

Reputation: 101

In order to call Calculate() through a BaseItem reference (i.e. polymorphism), BaseItem must have a Calculate() method. You basically have 3 options:

  1. Make BaseItem an interface:

    interface BaseItem //typically interfaces names are prefixed with I in C#
    {
        int Calculate();
    }
    
  2. Make BaseItem an abstract class (a class that cannot be instantiated directly because it doesn't provide a complete implementation):

    abstract class BaseItem
    {
          public abstract int Calculate();
    }
    
  3. Add a default implementation for Calculate to BaseClass:

    class BaseItem
    {
        public virtual int Calculate()  //Note the virtual keyword here
        {
            return 0;
        }
    }  
    

Upvotes: 3

Kinetic
Kinetic

Reputation: 2650

You've have to use the abstract keyword :

abstract class BaseItem 
{
    public abstract int Calculate();
}

class ItemA : BaseItem
{
    public override int Calculate()
    {
        return 0 + 1;
    }
}

class ItemB : BaseItem
{
    public override int Calculate()
    {
        return 1 + 1;
    }
}

void Main()
{
    BaseItem a = new ItemA();
    int result = a.Calculate();
}

Upvotes: 4

Related Questions