Personally I prefer to use the property where possible. This means you still get the validation, and you can easily put breakpoints on the property access. This doesn't work where you're trying to make a change to two properties which validate against each other - for instance, a "min and max" pair, where each has a validation constraint such that min <= max
at all times. You might have (C#):
public void SetMinMax(int min, int max)
{
if (max > min)
{
throw new ArgumentOutOfRangeException("max";
}
// We're okay now - no need to validate, so go straight to fields
this.min = min;
this.max = max;
}
At some point in the future, I'd like to see C# gain the ability to declare the backing field within the property, such that it's private to just the property:
public string Name
{
string name;
get { return name; }
set
{
if (value == null)
{
throw new ArgumentNullException("value");
}
name = value;
}
}
Outside the property, you wouldn't be able to get at name
at all, only Name
. We already have this for automatically implemented properties, but they can't contain any logic.