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
You could potentially use Convert.ToInt32(this._value)
or (int)((object)this._value)
. But in general if you find yourself having to check for specific types in a generic method, there's a problem with your design.
In your case, you probably should consider making an abstract base class, and then derived classes for the types you're going to use:
public abstract class GenericClass
where T : struct
{
protected T _value;
public void SetValue(T value)
{
this._value = value;
}
public abstract byte[] GetBytes();
}
public class IntGenericClass: GenericClass
{
public override byte[] GetBytes()
{
return BitConverter.GetBytes(this._value);
}
}