What is the proper type for the rowversion (timestamp) data type?
I know it is 8 bytes but i cannot find a link in MSDN which tell if it is a signed or unsigned long.
which code should I use, does it even matter?
byte[] SqlTimeStamp;
long longConversion;
longConversion = BitConverter.ToInt64(SqlTimeStamp,0);
TimeStamp = BitConverter.GetBytes(longConversion);
ulong ulongConversion;
ulongConversion = BitConverter.ToUInt64(SqlTimeStamp,0);
TimeStamp = BitConverter.GetBytes(ulongConversion);
It does matter. You want your comparison to have the same result as SQL Server's comparison. SQL Server uses unsigned comparisons on binary types:
If you do the same thing with
longwhich is signed,0xFFFFFFFFFFFFFFFFrepresents-1. That means your comparison will be incorrect; it won't match with the same comparison done in SQL Server.What you definitely want is to use
ulongwhere0xFFFFFFFFFFFFFFFFisulong.MaxValue.Endianness is also important
Additionally, as Mark pointed out,
BitConverter.GetUInt64is not converting properly. Mark is not completely right-BitConverteris either big-endian or little-endian depending on the system it's running on. You can see this for yourself. Also, even if BitConverter was always little-endian,Array.Reverseis less performant with a heap allocation and byte-by-byte copying.BitConverteris just not semantically or practically the right tool for the job.This is what you want:
The cleanest solution
Update: If you use .NET Core 2.1 or later (or .NET Standard 2.1), you can use
BinaryPrimitives.ReadUInt64BigEndianwhich is a perfect fit.On .NET Framework, here is the solution I use: Timestamp.cs. Basically once you cast to
Timestamp, you can't go wrong.