I have a generic class which saves value for the specified type T. The value can be an int, uint, double or float. Now I want to get the bytes of the value to encode it into an
I am on the side that this is an interesting real life problem that has nothing to do with "bad" design but rather standard C# limitations. Casting through object
return BitConverter.GetBytes((int)(object)this._value);
or, in the current language as
if (this._value is int intValue)
{
return BitConverter.GetBytes(intValue);
}
works but causes a performance hit due to ValueType boxing.
The solution to this problem is Unsafe.As
if(typeof(T) == typeof(int))
{
return BitConverter.GetBytes(Unsafe.As(ref this._value));
}
Results in no explicit or implicit cast to object
.