An oldie but a goodie. I like the technique that “arjay” outlined in his codeguru post (http://www.codeguru.com/forum/showthread.php?t=441772). However he noted a problem with the arrays that XSD.exe creates, namely you have to check for null every time you want to iterate over them. In the post he suggests hand editing the generated code. I am not a big fan of that. You can easily use a partial class to avoid needing to hand edit the code. Or you can use an extension method to encapsulate the check for you.
public static List<T> ToNonNullList<T>(this T[] items)
{
if (items == null)
return new List<T>();
return items.ToList();
}
BONUS:
So how do you get the xml in the first place, perhaps you have it in a string, or it might be coming from an URI. How about a little helper class that will Deserialize it for us. . . .
public class XSerializer
{
public static T Load<T>(string uri)
{
return LoadParse<T>(XDocument.Load(uri));
}
public static T Parse<T>(string xml)
{
return LoadParse<T>(XDocument.Parse(xml));
}
private static T LoadParse<T>(XDocument xDoc)
{
XmlSerializer serializer = new XmlSerializer(typeof(T));
using (XmlReader reader = xDoc.CreateReader())
{
return (T)serializer.Deserialize(reader);
}
}
}