Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Xml Serialization of ReadOnlyCollections

Tags:

c#

I have some container classes that expose their collections through a ReadOnlyCollection. Custom Methods are provided to Add and Remove from the collection which also perform some custom logic.

For example:

public class Foo
{
    List<Bar> _barList = new List<Bar>();

    public ReadOnlyCollection<Bar> BarList
    {
        get { return _barList.AsReadOnly(); }
    }

    public void AddBar(Bar bar)
    {
        if (bar.Value > 10)
            _barList.Add(bar);
        else
            MessageBox.Show("Cannot add to Foo. The value of Bar is too high");
    }
    public void RemoveBar(Bar bar)
    {
        _barList.Remove(bar);
        // Foo.DoSomeOtherStuff();
    }

}

public class Bar
{
    public string Name { get; set; }
    public int Value { get; set; }
}

This is all well and good but when i come to serialise Foo with the Xml Serializer an exception is thrown.

Can anyone offer a good way of going about this?

Thanks

like image 875
Cadair Idris Avatar asked Jun 30 '11 08:06

Cadair Idris


People also ask

What is XML serialization?

XML serialization is the process of converting XML data from its representation in the XQuery and XPath data model, which is the hierarchical format it has in a Db2® database, to the serialized string format that it has in an application.

Is XML serializable?

XML serialization can take more than one form, from simple to complex. For example, you can serialize a class that simply consists of public fields and properties, as shown in Introducing XML Serialization.

What is XML serialization in VB net?

The process of transforming the contents of an object into XML format is called serialization, and the reverse process of transforming an XML document into a . NET object is called deserialization. Page 2. An example. Let us take a C# class shown below (it could be VB.NET or any other .NET language for.

What is XML serialization and Deserialization?

Serialization is a process by which an object's state is transformed in some serial data format, such as XML or binary format. Deserialization, on the other hand, is used to convert the byte of data, such as XML or binary data, to object type.


1 Answers

Indeed, that won't work. So don't do that. Additionally, there are no hooks to detect xml serialization except the oh-so-painful IXmlSerializable.

So either:

  • don't use a read-only collection here
  • implement IXmlSerializable (tricky)
  • have a dual API (one read-only, one not; serialize the "not" - tricky as XmlSerializer only handles publicx members)
  • use a separate DTO for serialization
like image 87
Marc Gravell Avatar answered Oct 06 '22 16:10

Marc Gravell