.netserializabletype-safetyiserializable

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


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?


Solution

  • 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:

    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