I have an extension that implements all the BinaryReader/BinaryWriter in the Stream class. I want to create generic methods for them. Is there a nicer way of doing this?
public static void Write<T>(this Stream stream, T num)
{
if (num is byte)
{
stream.Write((byte)(object)num);
}
else if (num is Int16)
{
stream.Write((Int16)(object)num);
}
else if (num is Int32)
{
stream.Write((Int32)(object)num);
}
}
public static T Read<T>(this Stream stream)
{
object ret = null;
if (typeof(T) == typeof(byte))
ret = stream.ReadInt8();
else if (typeof(T) == typeof(Int16))
ret = stream.ReadInt16();
else if (typeof(T) == typeof(Int32))
ret = stream.ReadInt32();
if (ret == null)
throw new ArgumentException("Unable to read type - " + typeof(T));
return (T)ret;
}
Now using this for the Read method.
static Dictionary<Type, Func<Stream, object>> ReadFuncs = new Dictionary<Type, Func<Stream, object>>()
{
{typeof(bool), s => s.ReadBoolean()},
{typeof(byte), s => s.ReadInt8()},
{typeof(Int16), s => s.ReadInt16()},
{typeof(Int32), s => s.ReadInt32()},
{typeof(Int64), s => s.ReadInt64()},
{typeof(string), s => s.ReadString()},
};
public static T Read<T>(this Stream stream)
{
if (ReadFuncs.ContainsKey(typeof(T)))
return (T)ReadFuncs[typeof(T)](stream);
throw new NotImplementedException();
}