Serialization of ICollection(of t)

  • Thread starter Thread starter Sid Price
  • Start date Start date
S

Sid Price

I have a VB.NET 2005 class that implements ICollection(Of t):

Public Class SignalCollection
Implements ICollection(Of VM_Signal)

Public Sub Add(ByVal oSignal As VM_Signal) Implements ICollection(Of
VM_Signal).Add

....

End Sub

....

End Class

It implements all of the necessary methods and properties and seems to work
just fine. Now I need to serialize this object to an XML file and I am
trying to use XMLSerializer. Here is my code for that:

Dim x As XmlSerializer = New XmlSerializer(GetType(SignalCollection))
Dim writer As TextWriter
writer = New StreamWriter("MyFile.xml")
x.Serialize(writer, Me)
writer.Close()

When XMLSerializer object is created I get an exception:

System.InvalidOperationException was unhandled
Message="An error occurred creating the form. See Exception.InnerException
for details. The error is: To be XML serializable, types which inherit from
IEnumerable must have an implementation of Add(System.Object) at all levels
of their inheritance hierarchy. VM_Signals.SignalCollection does not
implement Add(System.Object)."

I have an Add method for my object so I do not understand what more I need
to add. All the documentation I can find relates to serializing ICollection
derived classes and not ICollection(Of t) objects. Any pointers to a sample
or documentation would be much appreciated.

Sid.
 
Sid said:
I have a VB.NET 2005 class that implements ICollection(Of t):

Public Class SignalCollection
Implements ICollection(Of VM_Signal)

Public Sub Add(ByVal oSignal As VM_Signal) Implements ICollection(Of
VM_Signal).Add
Your problem's right there: you've implemented Add() explicitly. This is an
odd thing to do, since there's no obvious reason to implement this method
explicitly. Your callers will have to cast the object to an ICollection(Of
VM_Signal) before they can call Add(), which is inconvenient to say the
least. Unless you have an unusual collection where adding elements directly
is not allowed, this should just be

Public Sub Add(ByVal oSignal As VM_Signal)

(And if adding elements really isn't allowed, Add() should be throwing an
exception anyway, whether it's explicitly implemented or not.)

The serializer is failing because it can't handle explicitly implemented
methods. The Add() method must be directly exposed on your type.
 
Back
Top