Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Single Digit Type

Tags:

.net

Is there a data type I can use to store a single digit, but nothing else. i.e. one of 0 - 9 and nothing else.

I know I could use short, int or long, but it's for the design of an api and I want to be clear that the user should only give me a single digit.

like image 490
ilivewithian Avatar asked Feb 16 '26 16:02

ilivewithian


2 Answers

Sounds like a good candidate for an enum type.

public enum Digit
{
    Zero, 
    One,
    Two,
    Three, 
    Four, 
    Five, 
    Six,
    Seven,
    Eight, 
    Nine
}

Benefits:

  1. Easily understood.
  2. Directly convertible to and from its underlying type

Disadvantage:

  1. Theoretically possible to create instances that don't belong in the [0 - 9] range since an enum instance can take any value of the underlying type.
like image 140
Ani Avatar answered Feb 18 '26 06:02

Ani


There are a few ways you could go.

  • Create your own value type
  • Use an enum - seems silly to enum 0 through 9 though
  • Just use a short and throw an exception if it's too large...

I think that latter would be the clearest in terms of an API. I would only created a new type if it's going to be used frequently throughout a large and complex API.

using System;
public class MyClass {
    public static void Main() {
        var test = new ApiClass();
        test.MyNum = 0; // OK
        test.MyNum = 1; // OK
        test.MyNum = 9; // OK

        test.MyNum = 10; // exception
        test.MyNum = -1; // exception
    }   
}

public class ApiClass {
    private short _myNum;
    public short MyNum {
        get {
            return _myNum;
        }
        set {
            if (value < 0 || value > 9)
                throw new ArgumentOutOfRangeException("Value must be between 0 and 9!");

            _myNum = value;
        }
    }
}
like image 40
Paul Sasik Avatar answered Feb 18 '26 08:02

Paul Sasik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!