In order for a class to be serializable, it must have the
attribute SerializableAttribute set and all its members must also be
serializable, except if they are ignored with the attribute
NonSerializedAttribute. However, the private and public members of a class are
always serialized by default. The SerializationAttribute is only used for the
binary serialization. The code snippet below shows the usage of
SerializableAttribute.
Listing1:
[Serializable]
public class Employee
{
public int empCode;
public string empName;
}
Note the Serializable attribute that is specified at the
beginning of the class in the code listing above. The SerializableAttribute is
useful for situations where the object has to be transported to other
application domains. It needs to be applied even irrespective of whether the
class implements the ISerializable interface. If this attribute is not set in
that case, then when we try to serialize an object the CLR throws a
SerializationException.