Generic Methods in C#

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.