Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drawbacks of marking a class as Serializable

Tags:

c#

asp.net

What are the drawbacks of marking a class as serializable?

I need to save my asp.net session in a db and it requires that the objects in the session are serializable.

Make sense.

But turns out that all I had to do was decorate that class with the [Serializable] attribute and it worked, so that means .NET already has the underlying infrastructure to make classes serializable. So why can't it just do it by default?

What's the need to mark it as such?

like image 691
HS. Avatar asked Aug 06 '09 03:08

HS.


People also ask

What are the disadvantages of serializable?

The Serializable interface does not offer fine-grained control over object access - although you can somewhat circumvent this issue by implementing the complex Externalizable interface, instead.

What are the advantages of Serialisation?

Some of its primary advantages are: Used for marshaling (traveling the state of an object on the network) To persist or save an object's state. JVM independent.

How do you mark a class as serializable?

The easiest way to make a class serializable is to mark it with the SerializableAttribute as follows. The following code example shows how an instance of this class can be serialized to a file. MyObject obj = new MyObject(); obj. n1 = 1; obj.

Is serializable attribute necessary?

It is not necessary to use this attribute if a given type implements the System. Runtime. Serialization. ISerializable interface, which indicates that a class provides its own methods for serialization.


1 Answers

So why can't it just do it by default?

Automatic serialization/deserialization might not suffice for the object. For example, the object might contain a field that holds the name of a local file, a pointer to memory, an index into a shared array, etc. While the system could typically serialize these raw values without trouble, deserialization could easily result in something that is not usable. In general, it is impossible for the system to figure this out on its own. By requiring you to mark the class with Serializable, you indicate that you have taken these considerations into account.

like image 144
Jason Kresowaty Avatar answered Sep 24 '22 15:09

Jason Kresowaty