List<T> has a private int field called _version that increments every time you perform an operation on the list. Unfortunately for me this field is also serialized during binary serialization, so two lists with identical content can generate different byte arrays.
What would be the easiest way to make the serialized byte arrays identical? Writing a SerializationSurrogate? Finding the field in the serialized byte array and setting it to zero? Manually traversing my object graph and setting _version to zero using reflection? Are there any serialization attributes I can use? Perhaps use a different collection class, which?
https://referencesource.microsoft.com/#mscorlib/system/collections/generic/list.cs
EDIT: Added code to clarify:
List<string> l1 = new List<string>();
List<string> l2 = new List<string>();
l1.Add("Hi");
l2.Add("Hi");
l2.Clear();
l2.Add("Hi");
byte[] b1 = Serialize(l1);
byte[] b2 = Serialize(l2); // Contents of b2 will not be the same as b1
public byte[] Serialize(object o)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, o);
return stream.ToArray();
}
}
// One UGLY way, I'm not happy with
private void ClearListVersion(object list)
{
if (list == null) return;
FieldInfo fieldInfo = list.GetType().GetField("_version", BindingFlags.NonPublic | BindingFlags.Instance);
fieldInfo.SetValue(list, 0);
}