Below is an example to serialize and deserialize an object using generics in C#:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
public class MyClass
{
public static void RunSnippet()
{
string test = "abc";
int number = 123;
WL(XMLSerializationUtility.SerializeObject(Encoding.UTF8, test));
WL(XMLSerializationUtility.SerializeObject(Encoding.UTF8, abc));
}
#region Helper methods
public static void Main()
{
try
{
RunSnippet();
}
catch (Exception e)
{
string error = string.Format("---\nThe following error occurred while executing the snippet:\n{0}\n---", e.ToString());
Console.WriteLine(error);
}
finally
{
Console.Write("Press any key to continue...");
Console.ReadKey();
}
}
private static void WL(object text, params object[] args)
{
Console.WriteLine(text.ToString(), args);
}
private static void RL()
{
Console.ReadLine();
}
private static void Break()
{
System.Diagnostics.Debugger.Break();
}
#endregion
}
public class XMLSerializationUtility
{
public static T DeserializeObject<T>( Encoding encoding, string xml )
{
try
{
using (MemoryStream memoryStream = new MemoryStream( StringToByteArray( encoding, xml ) ) )
{
using ( XmlTextWriter xmlTextWriter = new XmlTextWriter( memoryStream, encoding ) )
{
XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );
return (T)xmlSerializer.Deserialize( memoryStream );
}
}
}
catch
{
return default( T );
}
}
public static string SerializeObject<T>( Encoding encoding, T obj )
{
try
{
using(MemoryStream memoryStream = new MemoryStream())
{
using ( XmlTextWriter xmlTextWriter = new XmlTextWriter( memoryStream, encoding ) )
{
XmlSerializer xmlSerializer = new XmlSerializer( typeof( T ) );
xmlSerializer.Serialize( xmlTextWriter, obj );
memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
}
return ByteArrayToString( encoding, memoryStream.ToArray() );
}
}
catch
{
return string.Empty;
}
}
private static Byte[] StringToByteArray( Encoding encoding, string xml )
{
return encoding.GetBytes( xml );
}
private static string ByteArrayToString( Encoding encoding, byte[] byteArray )
{
return encoding.GetString( byteArray );
}
}
Source: http://www.dotnet-snippets.de/dns/objekt-serialisierung-SID1407.aspx