Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot deserialize an IComparable field for value types

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.

like image 917
mmd Avatar asked Sep 05 '25 13:09

mmd


1 Answers

It's a known bug and it's not fixed: http://connect.microsoft.com/VisualStudio/feedback/details/91177/de-serialization-of-an-instance-of-a-class-implementing-icomparable-does-not-work

like image 156
Adriano Repetti Avatar answered Sep 09 '25 15:09

Adriano Repetti