Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I write a list using BinaryWriter?

I want to use a generic WriteList(List value) function to write a List using the BinaryWriter. Here is the code I am using:

public void WriteList<T>(List<T> value)
{
    for (int i = 0; i < value.Count; i++)
    {
        _writer.Write(value[i]);
    }
}

The error I am receiving is:

 Error  1   The best overloaded method match for 'System.IO.BinaryWriter.Write(bool)' has some invalid arguments    
Error   2   Argument 1: cannot convert from 'T' to 'bool'   

The BinaryFormatter is absolutely not an option.

like image 517
LunchMarble Avatar asked Jul 20 '11 22:07

LunchMarble


2 Answers

I really don't think you can avoid BinaryFormatter. Because type T can be any complex type and each instance of T can represent a huge graph of variables on memory.

so the only solution you have is to convert your instance of T to the byte[] format and the simplest solution for that is: BinaryFormatter

Actually the reason .Write() method only accept primitive types is that it knows how to convert them directly to byte[] (using Convert.ToXXX()) but there is no way it could guess that for generic type T.

As a work around you can define an interface like this:

public interface IBinarySerializable
{
    byte[] GetBytes();
}

and then implement it in your class:

public class MyClass: IBinarySerializable
{
    public int X {get;set;}
    public byte[] GetBytes()
    {
        return BitConverter.GetBytes(X); // and anyother
    }
}

and change your method to this:

public void WriteList<T>(List<T> value) where T:IBinarySerializable
{
    for (int i = 0; i < value.Count; i++)
    {
        _writer.Write(value[i].GetBytes());
    }
}
like image 164
Mo Valipour Avatar answered Nov 05 '22 05:11

Mo Valipour


If you check out the docs for BinaryWriter you'll see it doesnt accept an argument of object (Writes primitive types), and the compiler is trying its best at an overload, and failing, since you can't cast your T to bool, or anything else that BinarwWriter would like.

You're going to have to convert your object into something the BinaryWriter will work with.

like image 41
jasper Avatar answered Nov 05 '22 06:11

jasper