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
What would GenericClass
do? Rather, it seems you have a discrete set of classes which know how to get their bytes, so make an abstract base class that does all of the common work, and then make 3 concrete class which override a method to specify the piece that changes between them:
public abstract class GenericClass
{
private T _value;
public void SetValue(T value)
{
_value = value;
}
public byte[] GetBytes()
{
return GetBytesInternal(_value);
}
protected abstract byte[] GetBytesInternal(T value);
}
public class IntClass : GenericClass
{
protected override byte[] GetBytesInternal(int value)
{
return BitConverter.GetBytes(value);
}
}
public class DoubleClass : GenericClass
{
protected override byte[] GetBytesInternal(double value)
{
return BitConverter.GetBytes(value);
}
}
public class FloatClass : GenericClass
{
protected override byte[] GetBytesInternal(float value)
{
return BitConverter.GetBytes(value);
}
}
This not only provides clean, strongly-typed implementations of your three known types, but leaves the door open for anyone else to subclass Generic
and provide an appropriate implementation of GetBytes
.