Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

What's the use of Serializable 1

Status
Not open for further replies.

jjjkkk77

Programmer
Jun 14, 2007
10
US
Hi guys,

Just got a noob question here:

Why does the designer of C# (and Java too) make it that you have to mark a class as Serializable (or inherit ISerializable) to be able to serialize it? What's wrong of being able to serialize any object when you want to without explicitly saying you want. Does this has something to do with how the object is going to be represented/optimized by the compiler?

By the way, I let BinaryFormatter serialize an ArrayList to a file and it succeeded. But when I look at the hierachy of inheritance it looks like none of ArrayList's superclasses are serializable? So why can I serialize it without error or did I missed somewhere where it was declared so?

Thanks
 
Actually, in .NET you don't have to implement ISerializable for an object to be serializable. You just have to set the Serializable attribute and the framework will handle the serialization for you. The ArrayList class has this attribute set, which is why you can serialize it. The ISerializable interface is only for when the default serialization isn't good enough and your object needs to control its own serialization.

As for why you can't just serialize anything, I suppose optimization may have something to do with it. However, the simple answer is that serialization just doesn't make sense for every object. What would happen if you were to serialize and deserialize a WebClient, a data adapter, a database connection, or a WinForms layout pannel? You'd probably end up with pretty broken object. In such cases, it's probably better for the operation to just fail immediately.
 
Or use [DataContract] and [DataMember] attributes in WCF.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top