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.

Difference between IComparable and IComparer Interfaces of .NET Framework

  • These two interfaces you have to implement if you want to be able to make custom sorting.
  • The object to be sorted will implement IComparable while the class that is going to sort the objects will implement IComparer.