A List<T>
should work just fine; having arrays on the object API is just going to cause pain:
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
public class Foo
{
private List<Bar> bars = new List<Bar>();
public List<Bar> Bars { get { return bars; } }
}
public class Bar {
public string Name { get; set; }
}
static class Program
{
static void Main()
{
Foo orig = new Foo { Bars = { new Bar { Name = "abc"},
new Bar { Name = "def"}}}, clone;
using(MemoryStream ms = new MemoryStream()) {
XmlSerializer ser = new XmlSerializer(orig.GetType());
ser.Serialize(ms, orig);
ms.Position = 0;
clone = (Foo)ser.Deserialize(ms);
}
clone.Bars.Add(new Bar { Name = "ghi" });
foreach (Bar bar in clone.Bars)
{
Console.WriteLine(bar.Name);
}
}
}
Alternatively, you could write an append extension method, but this is not an efficient way to manipulate lists of data:
using System;
public class Foo
{
public Bar[] Bars { get; set; }
}
public class Bar {
public string Name { get; set; }
}
static class Program
{
static T[] Append<T>(this T[] arr, T value)
{
Array.Resize<T>(ref arr, arr == null ? 1 : (arr.Length + 1));
arr[arr.Length - 1] = value;
return arr;
}
static void Main()
{
Foo obj = new Foo { Bars = new[] { new Bar { Name = "abc" }, new Bar { Name = "def" } } };
obj.Bars = obj.Bars.Append(new Bar { Name = "ghi" });
foreach (Bar bar in obj.Bars)
{
Console.WriteLine(bar.Name);
}
}
}