Assuming you want this behavior, you can consider some helper methods, for example
public static double ValidatePositive(double input, string name) { if (input <= 0) { throw new ArgumentOutOfRangeException(name + " must be positive"); } return input; } public static double ValidateNonNegative(double input, string name) { if (input < 0) { throw new ArgumentOutOfRangeException(name + " must not be negative"); } return input; }
Then you can write:
public double AirDensity { get { return _airDensity; } set { _airDensity = ValidationHelpers.ValidateNonNegative(value, "Air density"); } }
If you need it for different types, you can even make it general:
public static T ValidateNonNegative(T input, string name) where T : IComparable<T> { if (input.CompareTo(default(T)) < 0) { throw new ArgumentOutOfRangeException(name + " must not be negative"); } return input; }
Note that none of this is terribly i18n-friendly ...
Jon skeet
source share