Home > database >  C# : How to handle method that is implemented in derived classes but not in the parent class in a lo
C# : How to handle method that is implemented in derived classes but not in the parent class in a lo

Time:11-24

I have the following method in my class:

    public double ComputeCost()
    {
        double Cost = 0;
        foreach (GenericTask Task in this.GenericTasks){
            Cost  = Task.Compute();
        }

        return Cost;
        
    }

The issue is that the Compute method is only implemented in derived classes from GenericTask e.g. EngineeringTask and DevelopmentTask and therefore the above code does not compile.

How can I achieve what I want? I am new to C# and does not know the "clean way" to achieve this ? Shall I implement a dummy Compute method in the GenericTasks altough it will never compute anything because it lacks proper data ?

CodePudding user response:

Create an abstract method in the base class and have the derived classes override that method.

Base class:

public abstract double Compute();

Derived class:

public override double Compute()
{
    /* your class-specific implementation */
}

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/override

https://en.wikipedia.org/wiki/Virtual_function

  • Related