Which type should I use in C# to represent numbers?
Luca Bolognese, from the Microsoft C# team, has an interesting post that aims at providing answers to the following question: Which type should I use in C# to represent numbers?
Luca and the C# team try to provide a simple algorithm that can help when you are confused about the numeric types in .NET. It may not address every scenario, but it can be useful when you are lost between byte, short, int, uint, long, float, double, decimal, and their friends.
Here is the algorithm:
If you need fractions:
- Use decimal when intermediate results need to be rounded to fixed precision - this is almost always limited to calculations involving money.
- Otherwise use double - you will get the rounding of your calculations wrong, but the extra precision of double will ensure that your results will be good enough.
- Only use float if you know you have a space issue, and you know the precision implications. If you don't have a PhD in numeric computation you don't qualify.
Otherwise:
- Use int whenever your values can fit in an int, even for values which can never be negative. This is so that subtraction operations don't get you confused.
- Use long when your values can't fit in an int.
Byte, sbyte, short, ushort, uint, and ulong should only ever be used for interop with C code. Otherwise they're not worth the hassle.