Counting number of records – Int or UInt?
.NET, Misc December 14th, 2011Lets say, you wanted a count for the number of records/customers/orders/Whatever else you have in your database/rdbms/nosql database/file system, how would you achieve that? 99% of the time, you would use something like this:
public int CountNumberOfRecords()
{
// Fancy code goes in here that does what it should do.
}
But, is using int the right thing to do? Int(32) has possible values from -2,147,483,648 to 2,147,483,648 – do you really need the negative? I don’t know about you, but I never have a negative number of rows in my database!
What you should be using is :
public uint CountNumberOfRecords()
{
// Fancy code goes in here that does what it should do.
}
What is the difference I hear you ask? Well a UInt (UInt16, 32, 64) is an Unsigned Integer – it does not contain a “bit” that can be used to signify that the number is a positive or a negative – the max value now is 4,294,967,295 – double!
The only issue with using a uint is that it is not CLS compliant – in other words, other languages that use the .net framework might not support UInt, so you might have to decorate your methods with [CLSCompliantAttribute(false)]


Recent Comments