The following class implements example serialization routines for serializing simple types used throughout these samples.
public static class SampleSerializationExtensions
{
/// <summary>Extension method on System.Decimal to convert to byte[16]</summary>
public static byte[] GetBytes(this decimal value)
{
int[] ints = decimal.GetBits(value); //int[4]
byte[] bytes = new byte[16];
Buffer.BlockCopy(ints, 0, bytes, 0, 16);
return bytes;
}
/// <summary>Extension method on byte[] to convert to System.Decimal</summary>
public static decimal ToDecimal(this byte[] value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (value.Length != 16)
throw new ArgumentException("Expecting byte[16]", nameof(value));
int[] ints = new int[4];
Buffer.BlockCopy(value, 0, ints, 0, 16);
return new decimal(ints);
}
/// <summary>Extension method on System.Decimal to convert to byte[8]</summary>
public static byte[] GetBytes(this DateTime value) =>
BitConverter.GetBytes(value.ToBinary());
/// <summary>Extension method on byte[] to convert to System.Decimal</summary>
public static DateTime ToDateTime(this byte[] value)
{
if (value == null) throw new ArgumentNullException(nameof(value));
if (value.Length != 8)
throw new ArgumentException("Expecting byte[8]", nameof(value));
return DateTime.FromBinary(BitConverter.ToInt64(value, 0));
}
}