chmodder chmodder - 2 months ago 13
C# Question

How to pass fixed parameter to base constructor

What



I have this coding exercise where a base class constructor should be able to define a custom property value using input parameters, but the derived class should set this property to a fixed value.

A snippet of the exercise text:


  1. “ Define a class
    Manager
    … a manager also has a monthly bonus, which should be specified at construction…”

  2. “ Define a class
    Director
    . The
    Director
    class is supposed to be derived from the
    Manager
    class. A director is just a manager who has a fixed monthly bonus of 20000… When implementing the
    Director
    class, pay special attention to implementing the constructor correctly. Does the class need anything else than a constructor?



Question



So how can I set this fixed value in the derived class by only having a constructor in this class? Also: the creator of the subclass object should not be able to set this property (
monthlyBonus
) at all.

Attempt



//Manager inherits Employee (not interesting in this context)
public Manager(string name, int salaryPerMonth, int monthlyHours, int monthlyBonus) : base(name, salaryPerMonth)
{
MonthlyHours = monthlyHours;
Bonus = monthlyBonus;
}

public class Director : Manager
{
public Director(string name, int salaryPerMonth, int monthlyHours, int monthlyBonus = 20000) : base(name, salaryPerMonth, monthlyHours, monthlyBonus)
{
//base.Bonus = 20000;
}
}



  • I thought about removing the input parameter
    monthlyBonus
    in the
    Director
    class in make a variable inside the constructor, but since the base class constructor gets called first thats not going to work i guess.

  • I also thought about setting the input parameter value as an optional value but then the caller would be able to change this value, so this is not accepted either.


Set Set
Answer

you can directly pass values in base constructor

public class Director : Manager
{
    public Director(string name, int salaryPerMonth, int monthlyHours,)  
           :base(name, salaryPerMonth, monthlyHours, 20000)
    { 
    }
}