Note that there are some explanatory texts on larger screens.

plurals
  1. POProblems with DataContractSerializer - how to correctly serialize objects deriving from List<T>?
    primarykey
    data
    text
    <p>Observe the following sample code:</p> <pre><code>namespace A { [Serializable] internal class ComplexObject&lt;T&gt; : List&lt;T&gt;, IEquatable&lt;ComplexObject&lt;T&gt;&gt; where T : IEquatable&lt;T&gt; { private T m_state; internal T State { get { return m_state; } set { m_state = value; } } public bool Equals(ComplexObject&lt;T&gt; other) { // Implementation is omitted to save space. } } public static class Program { public static void Main() { var obj = new ComplexObject&lt;int&gt;(); 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&lt;int&gt;)serializer.ReadObject(stream); Debug.Assert(obj.Equals(copy)); } } } </code></pre> <p>Note that <code>ComplexObject&lt;T&gt;</code> derives from <code>List&lt;T&gt;</code>. </p> <p>Anyway, the last assertion fails. Replacing <code>[Serializable]</code> with <code>[CollectionDataContract]</code> and attaching <code>[DataMember]</code> to <code>m_state</code> yields the same negative result.</p> <p>It is as though the <code>DataContractSerializer</code> notices that the class is a collection and chooses to ignore its other state.</p> <p>Please advice anyone how to solve this issue given that:</p> <ul> <li>I would like to make as few changes to <code>ComplexObject&lt;T&gt;</code> as possible</li> <li>I am stuck with <code>DataContractSerializer</code> for reasons irrelevant for this question</li> </ul> <p>Thanks a lot in advance.</p> <p><strong>EDIT:</strong></p> <pre><code>public bool Equals(ComplexObject&lt;T&gt; other) { if (!m_state.Equals(other.m_state) || Count != other.Count) { return false; } bool result = true; for (int i = 0; i &lt; Count &amp;&amp; (result = this[i].Equals(other[i])); ++i) { } return result; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload