Hello, I've been struggling a bit using some of the methods in the FormatterServices class in conjunction with a ConcurrentBag.
Dim OriginalBag As New Concurrent.ConcurrentBag(Of Double) OriginalBag.Add(1.0) OriginalBag.Add(1.1) OriginalBag.Add(1.2) Dim BagFields As System.Reflection.MemberInfo() = FormatterServices.GetSerializableMembers(OriginalBag.GetType) Dim OriginalBagData As Object() = FormatterServices.GetObjectData(OriginalBag, BagFields) Dim NewBag As Concurrent.ConcurrentBag(Of Double) = FormatterServices.GetSafeUninitializedObject(GetType(Concurrent.ConcurrentBag(Of Double))) FormatterServices.PopulateObjectMembers(NewBag, BagFields, OriginalBagData) CollectionAssert.AreEquivalent(OriginalBag, NewBag)
The intended result the above is a new concurrent bag of doubles containing the same values as the original bag (similar to how using binary formatter to serialize/deserialize an object would work) however, the object NewList, in the end, has no members.
Tracing the issue back further, the GetSerializableMembers call only returns one member called "m_serializationArray". The GetObjectData method cannot find any fields named "m_serializationArray", returning only a list with a single Nothing in it.
I guess, with that in mind, my question is: is ConcurrentBag not intended to be used with the FormatterServices methods? I had just assumed that a ConcurrentBag would behave similarly to (for example) a List in this situation, but from the code above this appears to not be the case.
ConcurrentBag uses the OnSerializing/OnDeserialized mechanism for serialization, which means that its implementation actually provides code that runs to assist in the serialization/deserialization, rather than just specifying certain fields to be serialized/deserialized that completely represent its data. Just copying its serializable fields from one instance to another will not correctly populate the new instance.