Reputation: 1450
I am looking for an Attribute-written-code to specify the parameter range such as it works on a property. I need it on a method.
Analogy which exists (and works) for a property:
[Range(0,10)]
public int MyProperty{ get; set; }
Is there any analogy for a method? (below is my pseudocode):
[Range(0,10,"MyParameter")]
public void MyMethod(int MyParameter){...}
I know that there is the alternative
throw new ArgumentOutOfRangeException();
but I am asking for alternative in Attribute.
Any help?
Upvotes: 5
Views: 8059
Reputation: 149040
The syntax would look a bit like this:
public void MyMethod([Range(0,10)] int myParameter)
{
...
}
And thankfully, the built-in RangeAttribute
supports AttributeTargets.Parameter
, so this will compile. However, whether or not this is enforced depends entirely on how this is used. You'll need some kind of validation framework that checks the parameter for a valid range. The .NET framework will not do this for you automatically on all method calls.
Upvotes: 8
Reputation: 11717
Existing solutions that allow this:
public void MyMethod([Range(0, 10)] int MyParameter) { ... }
Upvotes: 0