Ashwani K
Ashwani K

Reputation: 8000

How to make a class serializable without Serializable attibute in .net

I have one debugger visualizer for seeing list of class object in the form of data table. But the limitation for the code is that the class should be serializable i.e. should be marked as [Serializable] and if the class is not marked Serializable then the debugger crashes. So, can anybody tell me how to make a class Serializable at run time if the class is not marked Serializable.

Upvotes: 3

Views: 6654

Answers (5)

Hans Passant
Hans Passant

Reputation: 942508

The fact that a class is missing [Serializable] can be explained two ways. It might be an error of omission, the more common case. Or the class can simply not support serialization. Which is not unusual, classes often depend on state that cannot be faithfully reproduced at deserialization time because it depends on global program state. Any of the Windows Forms controls would be a good example, they can't be deserialized without having a native Windows window that is in the required state, a state that often requires other windows to be created as well (like the container window) and many messages.

Well, this isn't going to help you implement your visualizer. You can't reliably implement it with serialization. Using reflection however gives you access to the same property and field values. And reflection is always supported.

Upvotes: 2

ram
ram

Reputation: 11626

If a class is not marked [Serializable], you can try serialization using SerializationSurrogate

Upvotes: 2

amelvin
amelvin

Reputation: 9061

You could look at your question differently, using [Serializable] allows you to use the dotnet libraries to serialize into json, xml etc. You can still serialize by writing your own methods to do so as fundamentally just about any data structure can be represented in xml or json format.

Adding [Serializable] to classes is one of the best practice tips in Bill Wagner's brilliant book Effective C#: 50 specific ways to improve your C#.

You can serialize a class without it being [Serializable] as @Darin (+1) pointed out you can't retrospectively redecorate a class. If I were you I'd put in [Serializable] as working around this is not worth the effort.

Upvotes: 1

Seb
Seb

Reputation: 2715

Any class with public get/set properties is XmlSerializable. Can you use XML serializers instead ?

Upvotes: 2

Darin Dimitrov
Darin Dimitrov

Reputation: 1039528

You cannot modify the metadata of an existing class at runtime.

Upvotes: 3

Related Questions