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
This is just long-hand for [Serializable]
. It tags the class as one that can be 'converted' to and from other formats.
Common examples include 'Serialization' of a class 'to' a JSON or XML data structure, and also the equivalent conversion 'from' such structures.
Consider a class
[Serializable]
class MyClass
{
public string Mem1 {get; set;}
public string Mem2 {get; set;}
}
...
MyClass mc = new MyClass;
mc.Mem1 = "Hello";
mc.Mem2 = "World";
When serialised to a JSON structure, we get:
"{'Mem1':'Hello','Mem2':'World'}"
And given the two-way nature of the process, if we recieved information of this format (e.g. back from some web service), then we could happily Serialize it back into an instance of this class.
Building on the JSON example, we find a series of classes in the namespace System.Web.Script.Serialization
that can help us with this. In particular, the JavaScriptSerializer
class helps us with the provision of Serialize()
and Deserialize
methods.
From the documentation:
Indicates that a class can be serialized
See the documentation for an example.
The System.SerializableAttribute specifies to the runtime that the instances of that class can be serialized
Eg. You return an object in a WCF service call. If that object has this attribute and all of the objects inside it are serializable, the runtime will transform that object to JSON or XML, depending on the type of resource the web service returns.
This is actually quite subtle...
On the surface, the answer is simply "it adds the SerialiableAttribute
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:
.custom instance
values (in IL terms)SerialiableAttribute
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.