Search code examples
c#javaserializationlanguage-designcloneable

Has the design of marker interfaces like Java's Serializable or Cloneable evolved in C#?


Java provides java.io.Serializable and java.lang.Cloneable in his standard library (and special support for it in the language and the JVM) for tasks around deserializing/serializing/cloning.

Has C# chosen a different path to provide this functionality, how does the implementation and code using it differ from Java and why was it done this way?

As an example, why does C# use both an attribute (annotation) and an interface for serialization?


Solution

  • .NET doesn't use ISerializable as just a marker interface. It acts not only as a marker, but also allows you to control exactly how .NET will serialize the class by implementing GetObjectData and a constructor which takes the suitable arguments.

    The attribute is used when the class can be serialized, but you don't want to define your own serialization behavior.

    So: Use ISerializable when you want to define your own serialization behavior; or use the [Serializable] attribute when you want to leave it up to the serialization formatter.

    Would I call it evolution? I don't know. .NET is just offering you different degrees of flexibility.