Often use SQL Identity as the ID of .NET objects.
Start the ID at 0 or 1 as don't want the objects to have negative IDs.
The ID is presented to users so it needs to be logical to humans.
Also often use something like ((Int32)key1 << 32) + key2; for hash
If unsigned can so with faster (UInt32)key1 << 32 | key2;
Since SQL does not have unsigned data type half the range is lost.
What is a good practice for converting from SQL signed to unsigned in .NET?
Where the convert goes from 0 to max.
A straight cast does not not work as (UInt16)Int16.Min = Int16.Max +1.
Need to convert Int16.Min to 0 and Int16.Max to UInt16.Max.
In SQL will set the Identity seed to minimum (or minimum +1) for the data type.
Currently have a situation where going to blow through Int32 max but doubt it will ever get past UInt32 max. If it does get past UInt32 max the app and database will need a full review.
Tried extensions to SqlDataReader and it seems to work.
Will post as an answer.
Not yet gone into production so checking SO for something better or warnings about the approach.
Don't need DataTable compatibility as this app uses zero and never will.
We don't use Entity Framework nor SQL LINQ. Grunge TSQL and SP.
public static class MyExtensions
{
public static UInt16 GetUInt16(this SqlDataReader rdr, int i)
{
//return (UInt16)rdr.GetInt16(i); // wrong answer
Int16 int16 = rdr.GetInt16(i);
UInt16 uint16 = (UInt16)(int16 + 32768);
return uint16;
}
public static UInt32 GetUInt32(this SqlDataReader rdr, int i)
{
Int32 int32 = rdr.GetInt32(i);
UInt32 uint32 = (UInt32)(int32 + 2147483648);
return uint32;
}
}