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
First off, this is a really bad code smell. Any time you're doing a type test on a type parameter like this odds are good you're abusing generics.
The C# compiler knows that you are abusing generics in this way and disallows the cast from the value of type T to int, etc. You can turn off the compiler getting in your way by casting the value to object before you cast it to int:
return BitConverter.GetBytes((int)(object)this._value);
Yuck. Again, it would be better to find another way to do this. For example:
public class NumericValue
{
double value;
enum SerializationType { Int, UInt, Double, Float };
SerializationType serializationType;
public void SetValue(int value)
{
this.value = value;
this.serializationType = SerializationType.Int
}
... etc ...
public byte[] GetBytes()
{
switch(this.serializationType)
{
case SerializationType.Int:
return BitConverter.GetBytes((int)this.value);
... etc ...
No generics necessary. Reserve generics for situations that are actually generic. If you've written the code four times one for each kind of type, you haven't gained anything with generics.