Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method parameter range

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?

like image 297
procma Avatar asked Feb 14 '23 04:02

procma


1 Answers

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.

like image 175
p.s.w.g Avatar answered Feb 24 '23 00:02

p.s.w.g