I am looking for a way to ensure that only serializable objects are stored into a Dictionary in C#.
To be more specific I’m looking to do something similar to this:
Dictionary<String, ISerializable> serialDict = new Dictionary<String, ISerializable>();
The problem with this is that I cannot store primitive types like integers, booleans, or strings.
Is there a way to ensure that my Dictionary contains only objects which can be serialized?
I don’t think you can do this at compile-time, but you can do it at runtime. If you build your own class deriving from
Dictionary<TKey, TValue>, then in the constructor of your class, you can check the attributes attached to theTValuetype, and make sureSerializableAttributeis one of them, else throw an exception.All of the standard primitive types (
int,bool, etc.) have this attribute.