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.