Serialization in c with example LEARNOVITA

C# Serialization Tutorial | Ultimate Guide to Learn [BEST & NEW]

Last updated on 16th Aug 2022, Blog, Tutorials

About author

Karan Baski (C# .Net Developer )

Karan Baski is a C# .Net Developer expert and subject specialist who has experience with Git, WPF,VB,.NET Framework,.NET Core, SVN,HTTP,.NET technology stack, WPF, C#, SQL server, Web API, ASP.NET. His articles help the learners to get insights about the Domain.

(5.0) | 19448 Ratings 2571

Introduction

In C#Serialization is the process of converting an object into byte stream so that it can be stored in memory, file or database. The reverse process of the serialization is called deserialization. Serialization is internally used in remote applications. Serialization is important as it stores the state of the object so that it can be recovered or recreated as and when it is required. This means that the object can be transferred to any remote location as needed using a web service by transferring the object from one domain to another.

C# SerializableAttribute

C# Serializable

To serialize the object, require to apply the SerializableAttribute attribute to the type. If you don’t apply the SerializableAttribute attribute to the type, a SerializationException exception is thrown at the runtime.

# Serialization example

Serialization in C# where we are serializing the object of Student class. To use BinaryFormatter.Serialize(stream, reference) method to serialize an object.

  • using System;
  • using System.IO;
  • using System.Runtime.Serialization.Formatters.Binary;
  • [Serializable]
  • class Student
  • {
  • int rollno;
  • string name;
  • public Student(int rollno, string name)
  • {
  • this.rollno = rollno;
  • this.name = name;
  • }
  • }
  • public class SerializeExample
  • {
  • public static void Main(string[] args)
  • {
  • FileStream stream = new FileStream(“e:\\sss.txt”, FileMode.OpenOrCreate);
  • BinaryFormatter formatter=new BinaryFormatter();
  • Student s = new Student(101, “sonoo”);
  • formatter.Serialize(stream, s);
  • stream.Close();
  • }
  • }

Uses for serialization

Serialization permits the developer to store 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 are:

  • Sending the object to a remote application by using the web service
  • Passing an object from one domain to the another
  • Passing an object through the firewall as a JSON or XML string
  • Manage security or user-specific information across applications

JSON serialization

JSON serialization

The System.Text.Json namespace includes classes for JavaScript Object Notation (JSON) serialization and deserialization. JSON is an open standard that is generally used for sharing data across the web. JSON serialization serializes the public properties of an object into a string, byte array, or stream that conforms to RFC 8259 JSON specification. To control the way of JsonSerializer serializes or deserializes an instance of class:

  • Used a JsonSerializerOptions object
  • Apply attributes from System.Text.Json.Serialization namespace to classes or properties
  • Implement the custom converters

Making an object serializable

For binary or XML serialization,:

  • Object to be serialized
  • A stream to include the serialized object
  • A System.Runtime.Serialization.Formatter instance

Apply the SerializableAttribute attribute to a type to denote that instances of the type can be serialized. An exception is thrown if you attempt to serialize but the type does not have the SerializableAttribute attribute. To prevent a field from serialized, apply the Non serialized Attribute attribute. If a field of a serializable type contains a pointer, a handle, or some other data structure that is a particular environment, and the field cannot be meaningfully reconstituted in a various environment, then want to make it nonserializable. If a serialized class includes references to objects of other classes that are marked SerializableAttribute, those objects will also be serialized.

Binary serialization

Steps for serializing an object are as follows:

    1. 1. Generate a stream object.
    2. 2 Generate a BinaryFormatter Object.
    3. 3. Call BinaryFormatter.Serialize() method.

Advantages of Binary Serialization

  • Objects can be deserialized from the same data serialized to.
  • Enhanced performance as it is faster and even more powerful in the sense that it offers support for difficult objects, read only properties and even circular references.

Disadvantage of Binary Serialization:

  • It is not simply portable to another platform.

Basic and custom serialization

  • Binary and XML serialization can be performed in 2 ways, basic and custom.
  • The object is automatically serialized using.NET in basic serialization.
  • The only need is that the class has the SerializableAttribute attribute applied.
  • The NonSerializedAttribute can be used to maintain specific fields from being serialized.
  • When using basic serialization, the versioning of objects may create issues.
  • Basic serialization is the simplest way to perform serialization, but it does not provide much control over the process.
  • In custom serialization, can specify exactly which objects will be serialized and how it will be done.
  • The class must be marked SerializableAttribute and implement a ISerializable interface
  • If you want an object to be deserialized in a custom manner as well, use a custom constructor.

Attributes in XML Serialization

Attributes in XML Serialization

Some important attributes in XML Serialization are:

XmlAttribute: Containing member will be serialized as a XML attribute

XmlElement: The field will be serialized as the XML element.

XmlIgnore: Field or property will ignored during Serialization

XmlRoot: It represent the XML document’s root Element Every XML has a root element. In XML serialization, the name of the root element is similar to the name of the class. XmlRoot attribute is used to offer a custom name to the root element of XML. The name of the class is Employee and have used [XmlRoot(“EmployeeDetail”)] before class declaration. Therefore the root element is converted to the EmployeeDetail in place of Employee.

XmlElement: XmlElement is used for various Tag names in XML. Use the XmlElement attribute to the class field or property. In the given code xml attribute [XmlElement(“EmpAddress”)] is used. So in the XML file EmpAddress will be displayed in place of Address.

Serialization of DataSet

Serialize a DataSet object to an XML file. The method for serialization of dataset is first to create a dataset and populate with data. Create a table using the DataTable object and then add the table into the DataSet object. Created the given below table named as Employee. can create the table according to the need.

    EmpID EmpNameAddress
    1. Raj Pune
    2. Swaraj USA

Designer serialization

  • Designer serialization is a special form of serialization that involves the type of object persistence associated with development tools.
  • Designer serialization is a process of converting an object graph into the source file that can later be used to recover the object graph.
  • A source file can contain code, markup, or even SQL table data.

The advantages of serialization :

  • The serialized stream can be encrypted, authenticated and compressed, supporting the requirement of secure Java computing.
  • Serialized classes can support coherent versioning and are flexible enough to allow gradual evolution of the application’s object schema.
  • Serialization can be used as a mechanism for changing objects between Java and C++ libraries, using third party vendor libraries (like RogueWave’s Tools.h++ ) within C++.
  • There are too many critical technologies that rely upon serialization, including RMI, JavaBeans and EJB.

Disadvantages :

  • It should ideally not be used with large-sized objects, as it provides significant overhead.
  • Large objects also significantly improve the memory requirements of the application since the object input/output streams cache live references to all objects written to or read from the stream until the stream is closed or reset. As a result, these items’ trash collection may be significantly delayed.
  • The Serializable interface does not offer fine-grained control over object access – although can somewhat circumvent this problem by implementing the complex Externalizable interface, instead.
  • serialization does not provide any transaction control mechanisms per se, it is not suitable for use within applications needing concurrent access without making use of additional APIs.

Serialization in .NET

The .NET Framework offers a few serialization mechanisms.:

XML Serialization –

  • serializes the public fields and properties of an object into the XML stream
  • XML serialization does not record or preserve data about the object’s original type or namespace.
  • The .NET Framework offers a class called the XmlSerializer.
  • This class provides methods with which can serialize the deserialized objects.

Binary Serialization –

  • serializes an object or an entire hierarchy of objects into the binary format
  • Binary serialization is a more efficient means of serializing .NET objects.
  • The BinaryFormatter class provides numerous methods that allow us to serialize and deserialize objects.

SOAP Serialization

  • serializes an object into a XML, but also serializes private members.
  • SOAP serialization does not support serialization of generic collections, but the SoapFormatter stores assembly and type information along with the data itself.
  • SOAP serialization is ideal for communications between heterogeneous applications, or applications that are written using different architectures, languages, platforms, etc.

The decision as to which kind to use is dictated by the needs of the application.

For example, XML and SOAP serialization produce XML output which is used across multiple platforms. Binary serialization in .NET should only be used in situations where the objects to be serialized and deserialized reside in namespaces that are usable and referenced by every application. If there is only one application in discussion, then binary serialization will offer a speedy, compact form of serialization that will be quite suitable. So it comes down to considering performance, storage type and location, and also extensibility.

Are you looking training with Right Jobs?

Contact Us

Popular Courses