You can mark a class as serializable using the SerializableAttribute. However, you can still serialize an object without marking it serializable. What is the impact of doing so?
-
1Sums it up pretty well...http://stackoverflow.com/questions/2595104/why-do-you-have-to-mark-a-class-with-the-attribute-serializable – Aaron McIver Nov 22 '10 at 22:15
3 Answers
I'm assuming that when you say "you can still serialize an object without marking it serializable" you mean that you're doing the serializing / deserializing yourself.
Adding the [Serializable] attribute indicates to 3rd party code that the object can be serialized. This is especially useful when you'd like to store an object in ASP.NET session, or in another tool (like a Memcached cache).

- 28,047
- 29
- 99
- 127
Putting [Serializable]
on a Type allows you to use it with the [System.Runtime.Serialization][1]
API's, which are pretty handy for the most common scenarios and spare you from writing a lot of repetitive code for serializing/deserializing your objects, which is usually cumbersome to test and error prone. And they gain you some flexibility in terms of the underlying storage mechanisms as well (such as Binary, XML, SOAP...).
If you put [Serializable]
on one of your Types, you should make sure it will serialize/deserialize properly using the standard mechanisms or you need to implement ISerializble
to control the process yourself. Things you should avoid serializing are e.g. event handler properties.
Most notably, when deciding whether to use Serializable or not is that you get a free serialization of the full object graph (root object plus all its associations and their associations), which would otherwise be very complex, especially if inheritance is involved. But for this to work, it requires you to have all your types in the graph marked Serializable
.

- 35,298
- 14
- 114
- 172
As I understand, you could use a surrogate to serialize an non serializable object, but what would prompt you to do so? I do not think private member's will be serialized using this approach. You likely need a default constructor, etc.

- 129
- 1
- 1
- 4