I investigated the binary serialization issue of the IComparable property, which causes the following error when a DateTime is assigned to the IComparable property:
Binary stream '0' does not contain a valid BinaryHeader.
The following code may cause this problem:
[Serializable]
public class SomeClassNotWorking
{
public SomeClassNotWorking(IComparable property)
{
Property = property;
}
public IComparable Property;
}
public class Program
{
static void Main(string[] args)
{
var instance = new SomeClassNotWorking(DateTime.Today);
var bytes = BinaryHelper.Serialize(instance);
BinaryHelper.WriteToFile("serialisedResults", bytes);
var readBytes = BinaryHelper.ReadFromFile("serialisedResults");
var obj = BinaryHelper.Deserialize(readBytes);
}
}
I solved the problem by replacing the IComparable property with a property of type T that implements IComparable:
[Serializable]
public class SomeClass<T> where T : IComparable
{
public SomeClass(T property)
{
Property = property;
}
public T Property;
}
It serializes and de-serializes without problems. However, why does serializing the IComparable property (when this property is a DateTime) cause the problem in the first place, in particular because DateTime supports IComparable? This also happens with ISerializable.
source
share