In C#, the
Month has a type of
int (a 32 bit signed integer) yet its range will only ever be 1-12. What are the reasons the C# team chose
int over a smaller numeric type such as
byte(8 bit unsigned integer)?
int is used for almost all integer variables in .NET although often a smaller type would be enough. Also, unsigned types are almost never used although they could be.
- Signed and unsigned types as well as integer types of different size can be awkward when combining them (
<for example). The rules are not obvious. I'm an experienced developer and I could not tell you the full set of rules. I do not need to know.
intis fast on all common architectures. Smaller types often result in conversions which can be slower.
- Performance is not an issue for 99% of typical code. No need to overthink this. Just use
- Readability is very good because the intention is clear. A
bytewould suggest binary data for example. (See comment by Flater.)
It's a useful convention to use
A month is not a value. A month is just a month.
The 1-12 mapping (which should have been 0-11 imo) is only made to make it easier to do math with it.
And once you start doing math with it, you have to be pragmatic. Ints are the defacto default for integer math. So use those.
It's what programmers expect. Without context: expect an int.
Because you're not interested whether January is 1 (or 0), you are interested in answers to questions like: "how many monthly installments till I paid of this debt". And then you find out that you should have used the integer instead of byte.