Ahh, ok. I understand the get/set thing now. So it is basically only to get nice structure to your code and make it more amintainable, but in effect does the same job as using variables and using functions or inline code to check for data.
Right.
Remember that in programming, Less is More.
The less code you write, the more time you have to do things other than maintain it.
So, you want fundamental business rules placed where every user of your class has no choice but to call it. So if you make the member variables private to the class (meaning outside users of the class can't access them), you then create public getters & setters, which users of your class
can access. You are then able to enforce some basic rules in the setter property.
If you have a need to use that value inside your class (in some other method), you then have a choice: You can access the private member variable directly, or you can call the public setter (which will enforce the rule for your class, too).
Code:
public class Employee
{
private decimal _SalaryHigh = 0.0m;
private decimal _SalaryLow = 0.0m;
public void Employee
{
// constructor
}
public decimal SalaryHigh
{
get
{
return _SalaryHigh;
}
set
{
if (value < SalaryLow)
{
throw new ArgumentOutOfRangeException("SalaryHigh");
}
_SalaryHigh = value;
}
}
public decimal SalaryLow
{
get
{
return _SalaryLow;
}
set
{
if (value > SalaryHigh)
{
throw new ArgumentOutOfRangeException("SalaryLow");
}
_SalaryLow = value;
}
}
public void SetSalaryInfo(decimal Low, decimal High)
{
// using internal member variable
// No range checking is done
_SalaryLow = Low;
_SalaryHigh = High;
// Using public setter property
// Setter will check ranges
this.SalaryLow = Low;
this.SalaryHigh = High;
}
}
Which to use, and when? It depends on the behavior you want.
Chip H.
If you want to get the best response to a question, please check out FAQ222-2244 first