Josh Lane on .NET RSS 2.0
 Thursday, March 01, 2007

Saw this post today describing basic guidance for when to use the different numeric data types available in C#, apparently from someone on the C# compiler team.

It's amazing how many developers go through life lacking even a basic understanding of the appropriateness of one numeric data type vs. another, for a given situation. I've found this to be especially true for financial applications... if I had a dollar for every time I saw floating point datatypes used in database schemas or source code to represent employee salaries, or bank account balances, etc., I'd own a ski house in Park City, like I'm always dreaming about. :-)

For the sake of completeness... if you're modeling flocks of birds or something, go ahead and use floating point types. But please do our collective profession a favor and use fixed point data types (that's System.Decimal in .NET, or decimal/money/smallmoney in SQL Server) if you're doing calculations involving money, or in general when rounding errors are not tolerable in your problem domain (like, you know, with money and stuff :-) ).

One more thing... the last line of advice reads this way:

Byte, sbyte, short, ushort, uint, and ulong should only ever be used for interop with C code. Otherwise they're not worth the hassle.

I'm pretty sure I can't agree with this, in particular for unsigned types. The author explains that unsigned types can be confusing, if you're not expecting values to wrap around from the lowest possible value to the highest. For example:

 

// some C# code...
uint x = 5;
uint y = 6;
uint z = x - y; // hmmmm...

Debug.Assert( z == uint.MaxValue );	// evaluates to true...

 

It's true that this will surprise some people the first time they see it. And I suppose with the unsigned types you're more likely to encounter this issue than with the signed types, since values close to zero occur more naturally "in the wild" (I guess)... but the fact remains that the signed data types work this way, too...

 

// more C# code...
int x = int.MaxValue;
int y = 1;
int z = x + y;

Debug.Assert( z == int.MinValue ); // again, true...

So I'm not sure what avoiding the unsigned types buys you, from the standpoint of avoiding this potential confusion. At the end of the day, it's probably best to simply understand how this stuff works, and don't arbitrarily limit your use of some language or platform feature only because someone else tells you it might be confusing.

Thursday, March 01, 2007 9:53:16 PM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
C#
Disclaimer

Don't blame my employer(s)... all of this is my fault.

© Copyright 2008 Josh Lane
Sign In
Locations of visitors to this page
DasBlog theme 'Business' created by Christoph De Baene (delarou)