Unable to deserialize IComparable field for value types

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:

/// <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 solved the problem by replacing the IComparable property with a property of type T that 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;
}

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.

+3
source share

All Articles