Hi,

One of the great features of C# is Generic Method. Back in sometime I wrote a Generic Method which serializes or de-serializes an object. The Generic methods are declared with type parameters. So here is the code snippet I wrote some time earlier:

public static void DoSerialization(Stream stream, SerializationType sType, ref T objToUse)
{
try
{
if (objToUse == null)
throw new Exception(“Missing object to serialize/De-serialize”);
XmlSerializer serializer = new XmlSerializer(typeof(T));
if (sType == SerializationType.Serialization)
serializer.Serialize(stream, objToUse);
else if (sType == SerializationType.DeSerialization)
objToUse = (T)serializer.Deserialize(stream);
}
catch (Exception ex)
{ //catching of exceptions
}
}

Let me explain this code. The method takes stream to be de-serialized or serialized depending upon the second argument. SerializationType is enum Type something like

public enum SerializationType
{
Serialization,
DeSerialization
};

and finally the reference of object to serialize or de-serialize. Well let me tell you due to support of type parameter, I was able to make a general function which will serialize or de-serialize any type of object and saved me from re-writing methods for different data type and at the same time its type safe as well 🙂

Isn’t it a great feature. If you do not use Generic Method, start considering them.

Categories: C#Generics

1 Comment

Adil Mughal · January 11, 2009 at 6:32 pm

Generic Methods at MSDN:
http://msdn.microsoft.com/en-us/library/twcad0zb.aspx

Leave a Reply to Adil Mughal Cancel reply

Avatar placeholder

Your email address will not be published. Required fields are marked *