Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way in C# that I can limit the range of an int variable?

Tags:

c#

I declare a variable like this:

public static int aBtn;

But the only valid values are 0,1,2,3,4 and 5

Is there any way that I can avoid any problems with my code later on my limiting it so that something like an exception will happen if I try to set the value to 6.

Note that I still want to be able to do things like:

aBtn = aBtn + 1; 
like image 860
Alan2 Avatar asked May 18 '19 09:05

Alan2


People also ask

What does if (!) Mean in C?

The !- operator negates a logical condition. In C, a numerical value of 0 is considered a logical false, any other numerical value a logical true. The !- operator negates a logical condition, so when pid is 0 it's true and when pid is not 0, it's false.

Which is not possible in C?

Returning a function pointer, Array of function pointer and Comparison of function pointer aren't possible in c.

Is not 0 true in C?

Boolean Variables and Data Type ( or lack thereof in C ) For interpretation, Zero is interpreted as false and anything non-zero is interpreted as true. To make life easier, C Programmers typically define the terms "true" and "false" to have values 1 and 0 respectively.

Is C very difficult?

It is not hard to learn C. Just like any other skill, you will need patience and resilience to master coding using C. The programming language features 32 keywords for its syntax. This makes it a relatively simple coding language to learn.


2 Answers

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;
}
like image 85
Jon Skeet Avatar answered Nov 02 '22 06:11

Jon Skeet


Couldn't you just use an enum with your only possible values? It's a good way to define small categorical sets.

For example:

 public enum RangedInt
{
    cero,
    one,
    two,
    three,
    four,
    five,
    six = 6
}
public class MyClass
{
    public RangedInt Field { get; set; }
}
like image 20
eestevanell Avatar answered Nov 02 '22 06:11

eestevanell