Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nesting base classes in c#

I have 3 classes, two inherit from 1:

public class Employee {
    private virtual double getBonus() { ... }
    private virtual double getSalary() { ... }
}

public class Nepotism : Employee {
    private double getBonus() { ... }
}

public class Volunteer : Employee {
    private double getSalary() { ... }
}

So the question is sometimes there will be a Volunteer who gets the Nepotism bonus - is there some way to write the constructors to allow overriding/nesting the base class like this:

Employee Bill = new Volunteer(new Nepotism());

I'm thinking something like:

public class Volunteer : Employee {
    private Employee _nest;
    public Volunteer(Employee nest) 
        : base() {
        _nest = nest;
        // now what?
    }
}

Basically I want some objects to have the overrides from both classes.

I would like to avoid writing the override methods to check for nested classes.

getSalary() {
    return (nest != null) ? nest.salary : salary; // I want to avoid this if I can
}

How can I do this? Am I on the right track? Am I off the rails?

like image 433
willoller Avatar asked Dec 03 '22 12:12

willoller


1 Answers

Instead of subclassing, you might want to consider using the Decorator Pattern.

It provides an alternative to subclassing, and it useful when you may need to add "multiple" pieces of additional functionality to a single instance of a class, which is exactly the scenario.

like image 76
Reed Copsey Avatar answered Dec 06 '22 02:12

Reed Copsey