Dear ladies and sirs.
Observe the following sample code:
namespace A
{
[Serializable]
internal class ComplexObject<T> : List<T>, IEquatable<ComplexObject<T>>
where T : IEquatable<T>
{
private T m_state;
internal T State
{
get { return m_state; }
set { m_state = value; }
}
public bool Equals(ComplexObject<T> other)
{
// Implementation is omitted to save space.
}
}
public static class Program
{
public static void Main()
{
var obj = new ComplexObject<int>();
obj.State = 100;
var stream = new MemoryStream();
var serializer = new DataContractSerializer(obj.GetType());
serializer.WriteObject(stream, obj);
stream.Flush();
stream.Seek(0, SeekOrigin.Begin);
var copy = (ComplexObject<int>)serializer.ReadObject(stream);
Debug.Assert(obj.Equals(copy));
}
}
}
Note that ComplexObject<T>
derives from List<T>
.
Anyway, the last assertion fails.
Replacing [Serializable]
with [CollectionDataContract]
and attaching [DataMember]
to m_state
yields the same negative result.
It is as though the DataContractSerializer
notices that the class is a collection and chooses to ignore its other state.
Please advice anyone how to solve this issue given that:
- I would like to make as few changes to
ComplexObject<T>
as possible - I am stuck with
DataContractSerializer
for reasons irrelevant for this question
Thanks a lot in advance.
EDIT:
public bool Equals(ComplexObject<T> other)
{
if (!m_state.Equals(other.m_state) || Count != other.Count)
{
return false;
}
bool result = true;
for (int i = 0; i < Count && (result = this[i].Equals(other[i])); ++i)
{
}
return result;
}