Home > OS >  Force a Class's float variable to be within range
Force a Class's float variable to be within range

Time:03-06

How can I enforce that the variable of a class can be set within a particular numerical range? For example, in my sample code below, I would like to enforce that the user can only be able to set a value between 0.0f to 1.0f for the variable DownsamplingScale.

public sealed class DownsampleData
{
    public float DownsamplingScale = 0.0f;
}

I am not looking for the Clamping type solution because I really need to tell the class user that he/she must set a value within the range of 0.0f to 1.0f at the time they are using my class (writing code i.e. before compilation).

There are several ways to deal with the situation during runtime. I need something that informs during/before compilation about the expected range.

CodePudding user response:

I need something that informs during/before compilation about the expected range.

It's not possible for the compiler to achieve that. The value might be read from a file and that file may not even exist at compile time, e.g.

var d = new DownsampleData();
d.DownsamplingScale(float.Parse(File.ReadAllText("file_on_customer_pc_only.dat")));

CodePudding user response:

You can create a property (or method) where the argument is of an unsigned integer type. You pick the the actual type based on how much precision you need. If you use

public byte DownsamplingScaleFactor {get; set;}

You will have 256 values to choose from. From the documentation you make it clear that the value 0 means "0%" and 255 means "100%". It will not be possible to use any lower or higher value than that since the chosen type only supports these ranges.

With the type byte you will have a precision of 1/256 (ignoring off-by-one issues). If you need higher precision, use any other unsigned integer type like ushort, uint or ulong.

  •  Tags:  
  • c#
  • Related