Forward Visibilty - Code Blog

Saturday, September 5, 2009

Serialization and Inheritance in C#

So there are many posts on serialization, but this code seems to work a little better :) I don't remember exact details, but let's just say it generically handles any types. And the best part it even works with inheritance. Just make sure you add the reference to the namespace System.Runtime.Serialization and put this code on your classes

   
[KnowType (typeof(Employee))] //Just examples of types that inherit from Person
[DataContract]
public class Person
{
[DataMember]
Public string FirstName {get;set}
Public string LastName {get;set}
}

.....
static void Main(string[] args)
{
var list = new List<person>();
list.Add(new Person() { FirstName = "Fred", LastName = "Flinstone" });
list.Add(new Person() { FirstName = "Barney", LastName = "Rubble" });
list.Add(new Employee() { FirstName = "Michal", LastName = "Cool" });
var ser=Serialize <list<person>>(list);
XmlDocument serialized= Deserialize<list<person>>(ser);
List<person> listOfPersons= object.Equals(des,list);
}

public static T Deserialize<t>(XmlDocument doc)
{
var xs = new DataContractSerializer(typeof(T));
object o = xs.ReadObject(new XmlTextReader(doc.OuterXml, XmlNodeType.Document, null));
return (T)o;
}

public static XmlDocument Serialize<t>(T obj)
{
var xs = new DataContractSerializer(typeof(T));
var ms = new MemoryStream();
try
{
xs.WriteObject(ms, obj);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
throw new ApplicationException(ex.Message);
}
ms.Flush();
ms.Position = 0;
var sr = new StreamReader(ms);
var doc = new XmlDocument();
doc.LoadXml(sr.ReadToEnd());
sr.Close();
ms.Close();
return doc;
}





No comments:

Post a Comment