Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize Objects using xmlSerializer.Serialize and IEnumerable objects

I have an object that holds an object that is definded as IEnumerable, i.e.

[Serializable]
[XmlRoot("MyObject")]
public class MyObject
{
    [XmlAttribute]
    public string Name { get; set; }

    [XmlArrayAttribute("Numbers")]
    public IEnumerable<string> Numbers { get; set; }
}

When I run the XmlSerializer.Serialize against the object, i.e.

        MyObject myObject = new MyObject() { 
            Name = "My Name" ,
            Numbers= new List<string>(){"One", "Two"}
        };



     var xmlSerializer = XmlSerializer.FromTypes(new[] 
{ typeof(MyObject) })[0];
            using (var xmlWriter = XmlWriter.Create(@"MyObject.xml"))
            {
                if (xmlWriter != null) xmlSerializer.Serialize(xmlWriter, myObject);
            }

I get

"Cannot serialize member SerializeObjects.MyObject.Numbers of type System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]] because it is an interface."

Which I understand that you can't serialize an interface.

Now for the question:

What is the best declaration for the "public IEnumerable Numbers { get; set; }"?

Should I use List<>, if not why not?

like image 847
Coppermill Avatar asked Apr 28 '10 13:04

Coppermill


People also ask

What is the correct way of using XML serialization?

XML serialization does not convert methods, indexers, private fields, or read-only properties (except read-only collections). To serialize all an object's fields and properties, both public and private, use the DataContractSerializer instead of XML serialization.

Why do we use XmlSerializer class?

XmlSerializer enables you to control how objects are encoded into XML. The XmlSerializer enables you to control how objects are encoded into XML, it has a number of constructors.


2 Answers

In general terms, you should use Collection<T> if you intend users of your class to be free to modify it, or ReadOnlyCollection<T> if you do not. It is not recommended to use List<T> in public interfaces (source).

However, as this class is for XML Serialization and thus presumably isn't used for any purpose other than representing XML as an object model, the rules don't really apply in the same way as a 'normal' API because it will have no consumers other than the XmlSerializer, and so it doesn't really matter that much what you use. I'd probably still stick to the recommendations though.

like image 200
Greg Beech Avatar answered Sep 18 '22 17:09

Greg Beech


If you don't mind the list being editable i.e. Adding/Removing publically then List<> would be fine. Otherwise, you should use ReadOnlyCollection

like image 41
James Avatar answered Sep 17 '22 17:09

James