How can I make a method to take only serializable objects?

65 Views Asked by At

Although there is an interface named ISerializable, it seems to purpose to customize details when a type is marked [Serializable] attribute. If I understood correctly, the [Serializable] attribute by itself does not touch anything on a type it is attached to, but at run-time things implementing IFormatter determine if a given object is marked [Serializble] attribute (through reflection? I guess). Also IFormatter.Serializble() method takes just any Object. Does it mean virtually every object in .NET can be serialized? If not, is there way to take only serializable objects and make a compile-time error if a non-serializable object is passed?

1

There are 1 best solutions below

0
On BEST ANSWER

No, there is no way to do this for all types that might be serializable, except perhaps by writing a custom Roslyn analyzer that applies the exact rules you want, and adds the warnings that you want. This is a lot of work, and it may be simpler to simply add unit tests / integration tests that cover the serialization scenarios that you intend to support.

Additional notes:

  • [Serializable] is a pseudo-attribute - it actually maps to an IL flag, not a regular attribute annotation, and additionally it is only used by some serializers (very much not all)
  • the serializers that use the ISerializable / IFormatter APIs are generally the last serializers you want to use for most general purpose scenarios - they are typically much more brittle and type-bound that other more forgiving serializers (json, xml, protobuf etc)

Does it mean virtually every object in .NET can be serialized?

No. However, different serializers have different rules for when things can be serialized, and those rules are often multiple and varied... i.e. it can look like X or like Y or like Z. As such, the only API that accepts all 3 is: object