Monday, January 19, 2009

How do i serialize generic type in .NET

A generic class that has generic type parameters as member can be marked for serialization.

However, the generic class is only serializable if the generic type parameters specified is serializable.

Presently .NET does not provide a mechanism for constraining a generic type parameter
to be serializable.

The workaround is to perform a single runtime check before any use of the type, and abort
the use immediatly, before any damage could take place.

You can place the runtime verification in the static constructor.

Example:
[Serializable]
class MySerializableClass
{
T m_T;
static MySerializableClass()
{
ConstrainType(typeof(T));
}
static void ConstrainType(Type type)
{
bool isSerializable = type.IsSerializable;
if(!isSerializable)
{
string msg = "the type" + type.FullName + "is not serializable";
throw new InvalidOperationException(msg);
}
}
}

The static constructor is invoked exactly once per type per application domain, upon the first attempt to instantiate an object of that type.

2 comments:

  1. Really good article. Good going Alok; follow my bolgs to at http://remove-uneccessary-files.blogspot.com/

    ReplyDelete
  2. Follow this too http://oopconcept.blogspot.com/

    ReplyDelete