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.
Sounds like a good candidate for an enum type.
public enum Digit
{
Zero,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine
}
Benefits:
Disadvantage:
There are a few ways you could go.
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;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With