Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C# property constraints

I have a following statement:

public int aValue { get; set; }
public int func() { return someNonConstantValue; }

is there a way to constraint it to the range from -5 to what func() returns?
I could use Math.Clamp but if I define the setter will I also need to provide the getter?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Yes, if you provide a setter you will also need a custom getter. By this should not be a problem:

private int _aValue;
public int aValue
{
   get => _aValue;
   set
   {
     int upperLimit = func();
     if(value < -5 || value > upperLimit )
     {
        throw new ArgumentOutOfRangeException("value", "should be between -5 and " + upperLimit);
     }
     _aValue = value;
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading