0

I'm trying to set up a property in a constructor that will store a minimum value of 7.50m when any value less than it is entered. The attributes have already been declared, I just need help with this if statement, everything compiles but when a value is entered < 7.5, it doesn't work...

public decimal PayRate
{
    get
    {
        return payRate;
    }

    set
    {  
        if (value <= 7.50m)
            payRate = 7.50m;
        else
            payRate = value;
    }
}

EDIT: Here's the code that enters the values... EDIT 2: The code following the namespace declaration, I can't change anything but add a property. It didn't get formatted.

static void Main(string[] args)
    {
        Employee e1 = new Employee("Chevy", "Jack", 'A', "987654321", 1.20m); }

And the namespace where everything is defined.

    public Employee(string lName, string fName, char mi, string ss, decimal pay)
    {
        firstName = fName;
        lastName = lName;
        MiddleInitial = mi;
        SSN = ss;
        payRate = pay;
    }
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1200789
  • 13
  • 2
  • 6

2 Answers2

2

I assume that you are having something like this.

    private decimal payRate;
    public decimal PayRate
    {
        get { return payRate; }
        // i avoid use of "if else" in situations like these
        set { payRate = (value <= 7.50m) ? 7.50m : value; }
    }

Which should work fine when you assign

    PayRate=6.5m // or any value less than 7.5

but if you assign

    payRate=6.5m // this won't work because you are assigning value directly to private  property.

this won't work because you are assigning value directly to private property.

Edit: Your set accessor won't get invoked if you set

    payRate=pay

inside the constructor. You can remove pay from the constructor argument and set it later once you create an instance of Employee.

    // create employee 
    Employee e1 = new Employee("Ford", "Joe", 'S', "123456789");

    // set the pay here
    e.PayRate=1.75m;   // this will invoke the set accessor and set value to 7.5m
Sid M
  • 4,354
  • 4
  • 30
  • 50
DotNetUser
  • 6,494
  • 1
  • 25
  • 27
1

Your setter is broken by design. A setter should either set the property to the assigned value, or throw an exception.

You should write:

public static readonly Decimal MinimumWage = 7.50m;

...

set
{  
    if(value<=MinimumWage)
      throw new ArgumentException(string.Format("Wage {0} must be at least the minimum wage of {1}",value,MinimumWage));
    payRate = value;
}
CodesInChaos
  • 106,488
  • 23
  • 218
  • 262