Is there any way in C# that I can limit the range of an int variable?
No. This is a good example of why exposing public fields is a bad idea - you have no control over how they're used.
If you change it into a property, you can validate the value in the setter:
// TODO: Use a better name than either foo or aBtn
private static int foo;
public static int Foo
{
get => foo;
set => foo = value >= 0 && value < 6
? value
: throw new ArgumentOutOfRangeException("Some useful error message here");
}
If you don't like using the conditional ?: operator there, you can use a block-bodied setter:
public static int Foo
{
get => foo;
set
{
if (value < 0 || value > 5)
{
throw new ArgumentOutOfRangeException("Some useful error message");
}
foo = value;
}
}
Or better, have a utilty method that validates a value and returns the input if it's in range, or throws an exception otherwise. You can then use something like:
public static int Foo
{
get => foo;
set => foo = Preconditions.CheckArgumentRange(nameof(value), value, 0, 5);
}
Here's a slightly modified version of CheckArgumentRange
from Noda Time. (The real version has a separate method to do the throwing, which I suspect is for performance reasons, to allow the comparison part to be inlined.)
internal static int CheckArgumentRange(
string paramName, int value, int minInclusive, int maxInclusive)
{
if (value < minInclusive || value > maxInclusive)
{
throw new ArgumentOutOfRangeException(paramName, value,
$"Value should be in range [{minInclusive}-{maxInclusive}]");
}
return value;
}