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 specific protocol. Therefore I want to use the method BitConverter.GetBytes() but unfortunately Bitconverter does not support generic types or undefined objects. That is why I want to cast the value and call the specific overload of GetBytes(). My Question: How can I cast a generic value to int, double or float? This doesn't work:
public class GenericClass<T>
where T : struct
{
T _value;
public void SetValue(T value)
{
this._value = value;
}
public byte[] GetBytes()
{
//int x = (int)this._value;
if(typeof(T) == typeof(int))
{
return BitConverter.GetBytes((int)this._value);
}
else if (typeof(T) == typeof(double))
{
return BitConverter.GetBytes((double)this._value);
}
else if (typeof(T) == typeof(float))
{
return BitConverter.GetBytes((float)this._value);
}
}
}
Is there a possibility to cast an generic value? Or is there another way to get the bytes?
If your only goal is to add the GetBytes method to these types, isn't it a much nicer solution to add them as extension methods like so:
If you really need you generic class for other purposes, just do the dirty "double typecast" like Eric mentioned where you typecast value to object first.