Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you have to mark a class with the attribute [serializable]?

Seeing as you can convert any document to a byte array and save it to disk, and then rebuild the file to its original form (as long as you have meta data for its filename etc.).

Why do you have to mark a class with [Serializable] etc? Is that just the same idea, "meta data" type information so when you cast the object to its class things are mapped properly?

like image 579
Blankman Avatar asked Apr 07 '10 18:04

Blankman


People also ask

What is the purpose of serializable attribute?

Uses for serialization Serialization allows the developer to save the state of an object and re-create it as needed, providing storage of objects as well as data exchange. Through serialization, a developer can perform actions such as: Sending the object to a remote application by using a web service.

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.

What is the purpose of serialization in C#?

Serialization in C# is the process of converting an object into a stream of bytes to store the object to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.


1 Answers

Binary serialization is pretty powerful, it can create an instance of a class without running the constructor and can set fields in your class that you declared private. Regular code can of course not do this. By applying the [Serializable] attribute, you explicitly give it the go-ahead to mess with your private parts. And you implicitly give that permission to only the BinaryFormatter class.

XML serialization doesn't need this kind of okay, it only serializes members that are public.

DataContractSerializer can serialize private members as well. It therefore needs an explicit okay again, now with the [DataContract] attribute.

like image 181
Hans Passant Avatar answered Sep 16 '22 14:09

Hans Passant