I'd like to restrict the value of a number parameter in a constructor to within a certain range.
I know the conventional way is to do something like the following:
public class Foo
{
public int MaxAmount { get; }
public int Amount { get; set; }
public Foo(int amount)
{
if (amount > MaxAmount) { Amount = MaxAmount; }
else if (amount < 1) { Amount = 1; }
else { Amount = amount; }
}
}
But what I don't like about this is that the caller doesn't know when the property gets set to something other than what was specified. I could return an exception instead of silently clamping the value, but that's not very friendly.
What I'd like is something akin to this:
public Foo(int(1, this.MaxAmount) amount) // Where int(minimumValue, maximumValue)
{
Amount = amount;
}
in which one wouldn't even be able to instantiate Foo with an unacceptable value - the framework would prevent it.
Is anything like this possible?
EDIT FOR CLARITY:
What I'm after is a means by which the parameter itself can carry and communicate the information about its constraints - in a 'baked in' fashion which might, for example, surface in Intellisense when you wrote the call. So, I'd avoid the work of even attempting to instantiate the class if the values for the parameters were not valid.
If, for example, the program is running and the user types a number (N) and presses a button which creates a new Foo with an illegal quantity of N, I now have an exception to handle and something to debug and fix. Why even allow it in the first place? If Foo has been explicitly defined as having an upper boundary of 4 for its Amount property, what's the point of allowing the developer to write Foo(5) when I could have informed him that the value he's passing is not valid at the time that he wrote it?
If there's some syntactic sugar, like ParameterConstraint or something, that is handled by the Framework for me so that I don't have to roll my own into every class I write, I think that would be very useful.