I have investigated an issue around binary serialization of a IComparable property which causes the following error when the IComparable property is assigned a DateTime:
Binary stream '0' does not contain a valid BinaryHeader.
The following code can produce this issue:
/// <summary>
/// This class is injected with an icomparable object, which is assigned to a property.
/// If serialized then deserializes using binary serialization, an exception is thrown
/// </summary>
[Serializable]
public class SomeClassNotWorking
{
public SomeClassNotWorking(IComparable property)
{
Property = property;
}
public IComparable Property;
}
public class Program
{
static void Main(string[] args)
{
// var comparable = new SomeClass<DateTime>(DateTime.Today);
// here we pass in a datetime type that inherits IComparable (ISerializable also produces the error!!)
var instance = new SomeClassNotWorking(DateTime.Today);
// now we serialize
var bytes = BinaryHelper.Serialize(instance);
BinaryHelper.WriteToFile("serialisedResults", bytes);
// then deserialize
var readBytes = BinaryHelper.ReadFromFile("serialisedResults");
var obj = BinaryHelper.Deserialize(readBytes);
}
}
I have resolved the issue by replacing the IComparable property with a type T property which implements IComparable:
/// <summary>
/// This class contains a generic type property which implements IComparable
/// This serializes and deserializes correctly without error
/// </summary>
/// <typeparam name="T"></typeparam>
[Serializable]
public class SomeClass<T> where T : IComparable
{
public SomeClass(T property)
{
Property = property;
}
public T Property;
}
This serializes and de-serializes without problems. However, why would serialization of an IComparable property (when that property is a DateTime) cause the issue in the first place, particularly as DateTime supports IComparable? This also happens with ISerializable.