Wednesday, February 28, 2007

Which type should I use in C# to represent numbers?

Luca Bolognese, from the Microsoft C# team, had an interesting post trying to provide an answer to the question: Which type should I use in C# to represent numbers?

Luca tries to provide a simple way to help you decide when you are confused about the numeric types in .NET, in case you are lost between byte, int, uint, long, float, double, decimal, and so on.

In short he says:

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.

Luca is a very knowledgeable guy and a good presenter that I had the pleasure to meet at TechNet Boston last year. He sounds like he just landed from Italy (which he mostly did :) and if you remember that TechNet was going on right uin the middle of the 2006 World Cup and that Italy ended up as World Champion, you can imagine that Luca was really perked up (to say the least!).

(Link)

No comments:

Post a Comment