chmodder
chmodder

Reputation: 184

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;
    }
}

Upvotes: 1

Views: 2127

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70671

The short answer is that you just need to change the constructor declaration:

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

I.e. omit (as you already did) the monthlyBonus parameter, and hard-code the value when you call the base constructor using base.

Since this is clearly a classwork exercise, I would encourage you to ask questions focused on why it is you weren't already aware that you could do this, so that you can understand better how the base() constructor invocation works.

For now, I'll just point out that it's essentially the same as any other method invocation, and you can do everything with it that you can in any other method invocation. The parameters can be any expression you want; they don't need to just be a repetition of the parameters in the derived constructor.

Upvotes: 1

Set
Set

Reputation: 49779

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)
    { 
    }
}

Upvotes: 1

Related Questions