XmlSerialize class inheriting from CollectionBase

S

Sunit Joshi

Hello All
I have a collection class inheriting from CollectionBase. However when
I try to serialize it I keep getting a message "You must implement a
default accessor on PersonColl because it inherits from ICollection."
even though I have a parameterless constructor.

Any help is greatly appreciated...

thanks
Sunit
(e-mail address removed)

using System;
using System.Collections;
using System.Xml.Serialization;
using System.IO;

public class Person
{
private string name;
private string address;

public Person()
{}
public Person(string name)
{
this.name = name;
}
[XmlElement]
public string Name
{
get{return name;}
set{name = value;}
}
[XmlElement]
public string Address
{
get{return address;}
set{address = value;}
}
}

public class PersonColl: CollectionBase
{
public PersonColl():base()
{}
public void Add(Person p)
{
this.List.Add(p);
}
[XmlArray("Persons"), XmlArrayItem(typeof(Person))]
public IList Persons
{
get{return this.List;}
}
}

public class Test
{
public static void Main()
{
string[] names = {"Rick Stacy", "Derek Smith"};
string[] addresses = {"42. Pine Meadow. #35", "23 Ridgeland Drv.
#4"};

PersonColl pc = new PersonColl();
for(int i=0; i<names.Length; i++)
{
Person p = new Person();
p.Name = names;
p.Address = addresses;
pc.Add(p);
}
try
{
TestColl(pc);
SaveXml(pc);
}
catch(Exception ex)
{
Console.WriteLine("\nError: " + ex.Message);
}
}

public static void TestColl(PersonColl pc)
{
foreach(Person p in pc)
Console.WriteLine(p.Name + "-->" + p.Address);
}

public static void SaveXml(PersonColl p)
{
TextWriter tw = new StreamWriter("Persons.xml");
XmlSerializer xs = new XmlSerializer(p.GetType());
xs.Serialize(tw, p);
tw.Close();
}
}
 
M

Mickey Williams

You don't need a default constructor - you need a default accessor. Try
using this boilerplate:

using System;
using System.Collections;

namespace Servergeek.Demos
{
[Serializable]
public class BoatCollection: CollectionBase
{
public int Add(Boat element)
{
return InnerList.Add(element);
}

public void Remove(Boat element)
{
InnerList.Remove(element);
}

public Boat this[int index]
{
get { return (Boat)InnerList[index]; }
}

public void CopyTo(Boat[] target, int index)
{
InnerList.CopyTo(target, index);
}

public int IndexOf(Boat element)
{
return InnerList.IndexOf(element);
}

public bool Contains(Boat element)
{
return InnerList.Contains(element);
}

public void Insert(int index, Boat element)
{
InnerList.Insert(index, element);
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top