Search code examples
.netserializationbinary-serialization

Serializable attribute .NET


I'm using Binary Serialization in .NET to clone objects. Any of my own classes I must mark with the <Serializable()> attribute in order for the serializer to process the class. However since this is a function that will be used on any object, I was wondering:

Is it possible to have the serializer serialize the object even if it isn't marked with the <Serializable()> attribute? If not, is there a way to "auto-apply" the attribute to any class?

Edit. My main concern is that I need to be able to clone POCO objects that already exist in the .NET Framework. Are all those already serializable as well?


Solution

  • Without knowing how a class is implemented, it isn't safe to serialize it, and doing so could lead to subtly-broken objects. That's why a class designer must intentionally add the Serializable attribute, letting the runtime know that this is a safe operation. Automatically adding that attribute to any class is probably a bad idea.

    If you really need to serialize a class that isn't Serializable, you can do it manually:

    1. Figure out some way to convert your problem class to and from an alternate representation.
    2. Use that other class for serialization, converting back and forth as necessary.

    Failing that, you should look at other ways of preserving state besides serialization.