C# Dictionary containing with only Serializable objects-Collection of common programming errors
One thing to consider is that in classes that are serializable are tagged with the SerializableAttribute as opposed to implementing an interface. From MSDN:
Any class that might be serialized must be marked with the SerializableAttribute. If a class needs to control its serialization process, it can implement the ISerializable interface.
What you would need to do is make your own class that implements the IDictioanry interface and every time someone calls add, use reflection to check if the element passed in has a serializable attribute (and throw an exception if it doesn’t).
Code would look something like
class MyDictionary : IDictionary
{
private Dictionary d;
public void Add(TKey key, TValue value)
{
if( value.GetType().IsSerializable )
{
d.Add(key, value);
}
else
{
throw new ArgumentException();
}
}
.....
}