Why should I not make a class Serializable?

Brad8118 picture Brad8118 · Mar 28, 2011 · Viewed 8.8k times · Source

I'm storing some objects in my viewstate and I was wondering if there are any disadvantages to making a class Serializable?

Is it bad practice to make all of the classes Serializable?

Answer

Slappy picture Slappy · Mar 29, 2011

Firstly. Avoid viewstate.

Generally serialization (textual) is used for transferring objects.

You should avoid marking any class as serializable that is not a DTO (Data transfer object) or message class. We do this for several reasons. What ever picks up your class in serialized format may not have the method information (which is in the original assembly) of a non DTO class. Secondly, a class may reference a resource (DB connection, file handle, etc) Do NOT serialize these, since de serialization does not re-establish resource connections and state, unless explicitly designed for, but is still a bad idea.

So in summary: Do NOT serialize when you have contextual methods and storing data for a thrid party to use. (Like a service response with methods is a bad idea). And do NOT serialize when the class contains a resource reference. Keep your serializable object clean from methods as much as possible. This might involve a little re factoring into a service type pattern.

Do serialize DTO's and messages.

This is more of a design choice.