0% found this document useful (0 votes)
36 views6 pages

Serialization

Serialization is the process of converting an object into a stream of bytes to store or transmit the object. It allows saving an object's state to recreate it later. There are two main types: binary serialization stores all member data compactly while XML serialization stores public fields and properties in a human-readable XML format. Developers can control serialization by attributes that specify how class members are serialized.

Uploaded by

omid.khyber2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views6 pages

Serialization

Serialization is the process of converting an object into a stream of bytes to store or transmit the object. It allows saving an object's state to recreate it later. There are two main types: binary serialization stores all member data compactly while XML serialization stores public fields and properties in a human-readable XML format. Developers can control serialization by attributes that specify how class members are serialized.

Uploaded by

omid.khyber2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

What is Serialization and why do we need a

serialization?
To persist an object and save it in a specified storage location like a physical
file or DataBase.
Serialization is the process of converting an object into a stream of bytes in
order to store the object or transmit it 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 .

XML Serialization in C#.Net


Serialization converts an object into a stream and then uses it either to save
it in a file or to send/transport over any communication channel.

How Serialization Works


This illustration shows the overall process of serialization.

The object is serialized to a stream, which carries not just the data, but
information about the object's type, such as its version, culture, and
assembly name. From that stream, it can be stored in a database, a file, or
memory.
Uses for Serialization
Serialization allows the developer to save the state of an object and recreate
it as needed, providing storage of objects as well as data exchange. Through
serialization, a developer can perform actions like sending the object to a
remote application by means of a Web Service, passing an object from one
domain to another, passing an object through a firewall as an XML string, or
maintaining security or user-specific information across applications.
Making an Object Serializable
To serialize an object, you need the object to be serialized, a stream to
contain the serialized object, and
a Formatter. System.Runtime.Serialization contains the classes necessary
for serializing and deserializing objects.
Apply the SerializableAttribute attribute to a type to indicate that
instances of this type can be serialized. A SerializationException exception is
thrown if you attempt to serialize but the type does not have
the SerializableAttribute attribute.
If you do not want a field within your class to be serializable, apply
the NonSerializedAttribute attribute. If a field of a serializable type
contains a pointer, a handle, or some other data structure that is specific to
a particular environment, and the field cannot be meaningfully reconstituted
in a different environment, then you may want to make it nonserializable.
If a serialized class contains references to objects of other classes that are
marked SerializableAttribute, those objects will also be serialized.

What is XML serialization in C#.Net?


As name suggests, a serialization technique in which an object will be
converted/saved into xml format or stream. To use serialization in xml we
needXmlSerializer class. This class is derived
from System.Xml.Serialization. Serialize and Deserialize are the two most
important methods that we use to serialize object to xml and then
again deserialize into object.
Things to remember while using xml serialization and deserialization in
c# -
i. Only public objects can be serialized in XML serialization. And hence it
is also called as Shallow serialization.
ii. Classes inherited from IEnumerable and ICollection can also be
serialized, however it serializes only collections and not public
properties.
iii. Private or read-only properties, Methods, Indexers cannot be serialized
using this xml serialization.
Vice versa of XML serialization is called as XML deserialization. In XML
serialization the object gets converted into xml stream/file,
and converting that xml stream/file to an object again is called as XML
Deserialization. XML Serialization and DeSerialization in C# are the
most important topics in .Net.
How to do XML Serialization?
There are many ways c# serialize object to xml.
XML Serialization of simple class object : Serialize the object into XML
as it is.
1. XML Serialization of a Class object containing many properties :
Serialize the object into XML as it is.
2. XML Serialization using XMLElement : Control the name of
properties using XMLElement in XML serialization. You can specify an
alternate name for properties of an object to save into XML.
3. XML Serialization of array of Objects : Serialize the array of objects
into XML.
4. XML Serialization of DataSet : Serialize a DataSet into XML.
A. XML Serialization of simple class object
Let’s take a simple example. Take a look at below class –
public class BasicSerialization
{
public String name = “C# Tutorials”;
}
Here BasicSerialization is a class that has only public field “name” with defualt
value “c# tutorial”. Now use below code (method) to serialize above class –
private static void BasicSerializationMethod()
{
// Create an instance of BasicSerialization class.
BasicSerialization serializeObject = new BasicSerialization();
// Create and instance of XmlSerializer class.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(BasicSerialization));
// Create an instance of stream writer.
TextWritertxtWriter = new StreamWriter(@”C:Serialization ExamplesBasicSerialization.xml“);
nbsp; // Serialize the instance of BasicSerialization
xmlSerializer.Serialize(txtWriter, serializeObject);
// Close the stream writer
txtWriter.Close();
}
What we have done here –
i. First we have created an object of a class BasicSerialization, the object
which we are going to serialize.
ii. Created an object of XmlSerializer of type BasicSerialization. This object will
then be used to serialize.
iii. Created an object of Text StreamWriter to save file in physical location.
iv. Called “Serialize” method of xmlSerializer class to happen a xml
serialization of above mentioned object.
v. Closed the TextWriter.
After serialization of an instance of above class, the xml at
location highlighted in above code would look a like –
<?xmlversion=“1.0“encoding=“utf-8“?>
<BasicSerialization>
<name>C# Tutorials</name>
</BasicSerialization>
Note: you might also get xml namespaces with root element.
B. XML Serialization of a Class object containing many
properties.
In this example, we are creating a new class “Camera” with two properties –
public class Camera
{
public string MakeModel { get; set; }
public string Price { get; set; }
}
Now, serialize object of this class using following code –
private static void SerializationCamera()
{
// Create an instance of Camera class.
Camera camera = newCamera();
// Assing values to it’s properties
camera.MakeModel = “Canon EOS-1D”;
camera.Price = “$5219″;
// Create and instance of XmlSerializer class.
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Camera));
// Create an instance of stream writer.
TextWriter txtWriter = newStreamWriter(@”C:Serialization
ExamplesBasicSerializationCamera.xml“);
// Serialize the instance of BasicSerialization
xmlSerializer.Serialize(txtWriter, camera);
// Close the stream writer
txtWriter.Close();
}
Here we are serializing the same way as we did in first example. The output
xml of this will be look a like –
<?xmlversion=“1.0“encoding=“utf-8“?>
<Cameraxmlns:xsi=http://www.w3.org/2001/XMLSchema-instance
xmlns:xsd=“http://www.w3.org/2001/XMLSchema“>
<MakeModel>Canon EOS-1D</MakeModel>
<Price>$5219</Price>
</Camera>
C. XML Serialization using XMLElement
If you closely look at the output xml file in above example, you will observe
that the element names in xml file are same as property name in class
definition. We can also define the element names with the use
of XmlElement attribute.
Now, look at below code, which is same as given above – only difference is
that we used XmlElement with property definition –
public class Camera
{
[XmlElement("CameraName")]
public string MakeModel { get; set; }
[XmlElement("CameraPrice")]
public string Price { get; set; }
}
Now again call the SerializationCamera() Method to generate the XML file as
below –
<?xmlversion=“1.0“encoding=“utf-8“?>
<Cameraxmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance“
xmlns:xsd=“http://www.w3.org/2001/XMLSchema“>
<CameraName>Canon EOS-1D</CameraName>
<CameraPrice>$5219</CameraPrice>
</Camera>
Observe the element names here. MakeModel is saved
as CameraName and Price is saved as CameraPrice.

Binary and XML Serialization


Either binary or XML serialization can be used. In binary serialization, all
members, even those that are read-only, are serialized, and performance is
enhanced. XML serialization provides more readable code, as well as greater
flexibility of object sharing and usage for interoperability purposes.
Binary Serialization
Binary serialization uses binary encoding to produce compact serialization for
uses such as storage or socket-based network streams.
XML Serialization
XML serialization serializes the public fields and properties of an object, or
the parameters and return values of methods, into an XML stream that
conforms to a specific XML Schema definition language (XSD) document.
XML serialization results in strongly typed classes with public properties and
fields that are converted to XML. System.Xml.Serialization contains the
classes necessary for serializing and deserializing XML.
You can apply attributes to classes and class members in order to control the
way the XmlSerializer serializes or deserializes an instance of the class.
SOAP Serialization
XML serialization can also be used to serialize objects into XML streams that
conform to the SOAP specification. SOAP is a protocol based on XML,
designed specifically to transport procedure calls using XML. As with regular
XML serialization, attributes can be used to control the literal-style SOAP
messages generated by an XML Web service.
Basic and Custom Serialization
Serialization can be performed in two ways, basic and custom. Basic
serialization uses the .NET Framework to automatically serialize the object.
Basic Serialization
The only requirement in basic serialization is that the object has
the SerializableAttribute attribute applied.
The NonSerializedAttribute can be used to keep specific fields from being
serialized.
When you use basic serialization, the versioning of objects may create
problems, in which case custom serialization may be preferable. Basic
serialization is the easiest way to perform serialization, but it does not
provide much control over the process.
Custom Serialization
In custom serialization, you can specify exactly which objects will be
serialized and how it will be done. The class must be
marked SerializableAttribute and implement the ISerializable interface.
If you want your object to be deserialized in a custom manner as well, you
must use a custom constructor.
Designer Serialization
Designer serialization is a special form of serialization that involves the kind
of object persistence usually associated with development tools. Designer
serialization is the process of converting an object graph into a source file
that can later be used to recover the object graph. A source file can contain
code, markup, or even SQL table information.

You might also like