Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [System.SerializableAttribute()] do

Tags:

I am looking at somebody elses C# code and before a public enum there are the following lines:

[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.1")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true)] [System.Xml.Serialization.XmlRootAttribute(Namespace="", IsNullable=false)] 

Can somebody explain in plain english what the SerializableAttribute line are does?

I already came across this page - it didn't make much sense to me - I'm new at C#.

like image 827
Graham Avatar asked Sep 17 '12 14:09

Graham


People also ask

What does system serializable do?

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.

What is the purpose of serialization in Java?

Serialization in Java allows us to convert an Object to stream that we can send over the network or save it as file or store in DB for later usage. Deserialization is the process of converting Object stream to actual Java Object to be used in our program.

How many types of serialization are there in C#?

There are three types of serialization in . Net : Binary Serialization, SOAP Serialization and XML Serialization. Binary serialization is the process where you convert your . NET objects into byte stream.


1 Answers

This is actually quite subtle...

On the surface, the answer is simply "it adds the SerializableAttribute to the metadata for the class", where the purpose of SerializableAttribute is to advertise (to things like BinaryFormatter) that a type can be serialized. BinaryFormatter will refuse to serialize things that aren't explicitly advertised for serialization. This may be a consequence of BinaryFormatter being used to implement remoting, and to prevent data accidentally leaking across a remoting boundary.

Note that most serializers don't care about SerializableAttribute, so this only impacts things like BinaryFormatter. For example, none of XmlSerializer, DataContractSerializer, JavaScriptSerializer, JSON.NET or protobuf-net really care about SerializableAttribute.

However, actually, it is not a standard attribute, but has special handling by the compiler:

  • most attributes are technically .custom instance values (in IL terms)
  • however, SerializableAttribute actually maps to a CLI .class flag, serializable

This doesn't change the meaning, but : as a novelty fact, SerializableAttribute is not actually implemented as an attribute.

like image 136
Marc Gravell Avatar answered Sep 22 '22 02:09

Marc Gravell