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?
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.
In terms of drawbacks, The primary disadvantage of serialization is the performance overhead (both CPU and the disk) and the potential latency issues when sending it over the wire. There may be slight concerns with security because in general, XML serialization is insecure since it works only on public properties and classes, forcing you in some cases to exposed properties you may not have otherwise. Of course if security is really a concern, you probably wouldn't be storing too sensitive of data in session.
If you are using Silverlight, one potential drawback is that Silverlight does not support the [Serializable] attribute, so any classes decorated with it would be unusable for your Silverlight assemblies.
That said, for session management, small objects stored in the ASPState database typically perform just fine without any noticeable difference over in memory session. On the opposite end of the spectrum, I have had large objects with lists of other objects as properties etc, and if they are big enough, the performance hit can be noticeable at times.