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

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

Last updated on 01st Feb 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, and ASP.NET. His articles help the learners get insights into the domain.

(5.0) | 18147 Ratings 1519
    • Introduction to C# serialization
    • C# Serialization example
    • Serialization in C#
    • How C# Serialization Workst
    • Different types of serialization
    • Serialization format
    • Uses of C# serialization
    • Disadvantage
    • Conclusion

    Subscribe For Free Demo

      Introduction to C# serialization

      In C#, serialization is the process of converting an object into a byte stream so that it can be stored in memory, a file, or a database. The reverse process of serialization is called deserialization.

      Serialization is used internally by remote applications.

      C# SerializableAttribute

      To serialize an object, you need to apply the SerializableAttribute attribute to the type. If you do not apply the SerializableAttribute attribute to the type, a SerializationException exception will be thrown at run time.

      C# Serialization example

      Let`s see the simple example of serialization in C# where we are serializing the object of Student class. Here, we are going to use BinaryFormatter.Serialize(stream, reference) method to serialize the object.

      As you can see, the serialized data is stored in the file. To get the data, you need to perform deserialization.

      Serialization in C#

    • The manner of serialization includes the conversion of any item right into a circulation of bytes. This is achieved to transmit the item to the memory, record or database. The opposite of this manner is referred to as deserialization because it includes analyzing the item from the circulation of bytes.

    • Serialization is pretty critical because it saves the kingdom of the item in order that it is able to be recovered or recreated as and while it's miles required. This method that the item may be transferred to any far flung vicinity as required the use of an internet provider via way of means of moving the item from one area to another.

    • Course Curriculum

      Learn Advanced C and C Plus Plus Certification Training Course to Build Your Skills

      Weekday / Weekend BatchesSee Batch Details

      Example of Serialization

      The SerializableAttribute is carried out is carried out to serialize the item. If this isn't always achieved efficaciously then a SerializableException is thrown on the runtime.

      The following article presents an define on C# Serialization. The manner via way of means of which the item example is transformed right into a records circulation is referred to as serialization and the kingdom of the item example is transformed into records circulation due to the fact it is able to be transported throughout extraordinary networks made to be endured in a vicinity of garage. This serves as a bonus of serialization to transmit the transformed records circulation throughout extraordinary networks in a layout well matched on go structures and saves the transformed circulation records right into a medium of garage in a continual or nonpersistent item kingdom in order that the equal reproduction may be created withinside the later time.

      Steps of C# Serialization Object

      Given beneath are the stairs of C# Serialization Object:

    • A circulation item is created.
    • A BinaryFormatter item is created.
    • Serialize( ) technique is referred to as.

    • Advantages of Binary Serialization

      The item can be de-serialized from similar information you serialized it to. Upgraded execution as it is quicker and, surprisingly, more impressive as in it offers help for complex articles, read-just properties, and, surprisingly, round references.

      The burden of Binary Serialization:

      It isn’t effectively compact to another stage.

      Steps of C# Serialization Object

      Given underneath are the means of C# Serialization Object:

    • A stream object is made.
    • A BinaryFormatter object is made.
    • Serialize( ) strategy is called.

    • Working of C# Serialization

      1. Whenever we are working with applications, it is important to store the information in a medium that is either diligent or non-tenacious so similar information can be recovered later. This can be accomplished by utilizing the idea of Serialization.

      2. The method involved with changing over a case of the article into a byte stream moving the condition of the item into the memory or data set of the record is called Serialization.

      3. Serialization is fundamental to communicate the article across the organization to cross stages in a viable arrangement.

      4. A clone of an article can likewise be made utilizing Serialization.

      5. Runtime. Serialization namespace should be remembered for the program to utilize Serialization in C#.

      6. [ Serializable ] trait is utilized to make a class Serializable in C#.

      Given underneath are the kinds of serialization that are upheld by C#:

      Binary Serialization

      a) The quickest of the relative multitude of methods of serialization is Binary serialization.

      b) An item can be serialized to a parallel stream utilizing Binary Serialization.

      c) The personality of the article is saved while the item is serialized to a result stream utilizing double serialization.

      d) Framework. Runtime. Serialization. Formatters. The double namespace should be remembered for the program to utilize paired serialization.

      SOAP Serialization

    • Straightforward Object Access Protocol is the condensing of SOAP.
    • We utilize Simple Object Access Protocol Serialization assuming we need to move the items from one application to another application which is made of models that are heterogeneous.
    • Convertibility is the principal advantage of utilizing Simple Object Access Protocol Serialization.
    • An article can be serialized as Simple Object Access Protocol utilizing Simple Object Access Protocol Serialization.
    • Framework. Runtime. Serialization. Formatters. Cleanser namespace should be remembered for the program to utilize Simple Object Access Protocol serialization.

    • XML Serialization

      1.The public individuals from the occurrence of a class can be serialized into an XML stream utilizing XML Serialization.

      2.The speed of XML Serialization is exceptionally slow when contrasted with the speed of twofold Serialization.

      3.Cross-stage support is given by utilizing XML Serialization.

      4.XML Serialization depends on the text.

      5.XML Serialization is effectively lucid.

      6.XML Serialization is effectively editable.

      7.A property can be set on XmlAttribute to serialize the property utilizing XML Serialization.

      How C# Serialization Works

      Whenever you work with your application, you need to save the data to persistent or non- persistent media so that you can retrieve the same data later. This can be achieved by using the concept of serialization. The process of converting an instance of an object into a stream of bytes and moving the state of the object to the memory or database of the file is called serialization.

      Serialization is essential for sending objects to cross-platform platforms in a compatible format over the network. You can also clone objects by serialization. To take advantage of C# serialization, you must include the Runtime.Serialization namespace in your program. The [Serializable] attribute is used to make the class serializable in C#. Sample class showing [Serializable] class:

      • Code:
      • [Serializable] public class Check
      • {{
      • public int code;
      • Public string name.

      If you want to prevent the members of the class from being serialized, you can use the NonSerialized () attribute.

      Different types of serialization

      The Microsoft .NET Framework offers a great variety of possibilities for serializing objects. This chapter focuses on XML serialization, but before we dive into the details, let's take a quick look and compare the different serialization methods offered.

      XML Serialization

      XML XML serialization allows you to shrink an object's public properties and fields into an XML document that describes the publicly visible state of the object. This method serializes only public properties and fields. XML serialization may not match the original object in all cases because private data is not preserved.

      However, because the format of persistence is XML, the stored data can be read and manipulated in different ways on multiple platforms. The advantages of

      Course Curriculum

      Get JOB Oriented C and C Plus Training for Beginners By MNC Experts

      • Instructor-led Sessions
      • Real-life Case Studies
      • Assignments
      Explore Curriculum

      XML serialization are:

    • You have complete and flexible control over the format and schema of the XML generated by serialization.
    • Serialized formats are both human readable and machine readable.
    • Easy to implement. No custom serialization related code is required for the object to be serialized. The XML Schema Definition Tool (xsd.exe) can generate an XSD schema from a set of serializable classes and a set of serializable classes from an XSD schema, so almost any XML in an object- oriented program. You can easily define the data. Edit fashion (not XML oriented).
    • The object to be serialized does not need to be explicitly configured for serialization via either the SerializableAttribute or the implementation of the ISerializable interface.

    • XML serialization limits include:

    • Serialized classes require a default (no parameter) public constructor.
    • Read-only properties are not saved.
    • Only public properties and fields can be serialized.

    • Serialization format

    • Xerox Network Systems' Courier technology influenced the first popular standards in the early 1980s. Sun Microsystems released External Data Representation (XDR) in 1987. [6] XDR is an open format and is standardized as STD 67 (RFC 4506).

    • In the late 1990s, alternatives to the standard serialization protocol began to be pushed. We used XML, a subset of SGML, to generate a human-readable text-based encoding. Such encodings are useful for persistent objects that can be read, understood, and communicated with other systems by humans, regardless of the programming language.

    • The downside is that it loses the more compact byte stream-based encoding, but at that point it had less file size issues than early computers due to its large storage and transmission capacity.

    • YAML is a strict JSON superset that includes additional features such as data type tagging, support for non-hierarchical data structures, options for structuring data using indentation, and multiple formats of scalar data citations. Certain binary serialization standards (eg HDF, netCDF and older GRIB.

    • Given beneath are the kinds of serialization which might be supported via way of means of C#:

      1. Binary Serialization

      Binary serialization permits the serialization of an item right into a binary move, and recuperation from a binary move into an item. This technique may be quicker than XML serialization, and the binary illustration is generally a great deal greater compact than an XML illustration. However, this overall performance comes on the price of cross-platform compatibility and human readability.

      The advantages of binary serialization encompass the following:

    • It`s the quickest serialization technique as it does now no longer have the overhead of producing an XML report in the course of the serialization process.
    • The ensuing binary records is greater compact than an XML string, so it takes up much less garage area and may be transmitted quickly.
    • Supports both gadgets that put into effect the ISerializable interface to manipulate its personal serialization, or gadgets which can be marked with the SerializableAttribute attribute.
    • Can serialize and repair private and public individuals of an item.

    • The regulations of binary serialization encompass the following:

    • The elegance to be serialized need to both be marked with the SerializableAttribute attribute, or need to put into effect the ISerializable interface and manage its personal serialization and deserialization.

    • The binary layout produced is unique to the .NET Framework and it can't be without problems used from different structures or platforms.

    • The binary layout isn't always human-readable, which makes it greater hard to paintings with if the unique application that produced the records isn't always to be had.

    • 2. Other Forms of Serialization

    • A wide variety of different sorts of serialization are to be had in the .NET Framework which can be both now no longer meant for use at once or are unique to a hassle domain, that is out of doors the scope of this book.

    • These different serialization techniques encompass the LosFormatter, that is used to serialize and deserialize web page view kingdom in ASP.NET, the CodeDomSerializer, that is used to serialize an item graph representing dynamically generated supply code, the binary serialization used in .NET Remoting, and others.

    • The quickest of all of the strategies of serialization is Binary serialization. An item may be serialized to a binary circulation the use of Binary Serialization.

    • The identification of the item is preserved at the same time as the item is serialized to an output circulation the use of binary serialization. System. Runtime. Serilaization. Formatters. Binary namespace have to be blanketed withinside the application to utilize binary serialization.

    • 3. SOAP serialization

    • Simple Object Access Protocol is an abbreviation for SOAP. If you want to switch an item from one utility to any other with a heterogeneous architecture, use Simple Object Access Protocol Serialization. Portability is the primary benefit of the use of Simple Object Access Protocol serialization.

    • Objects may be serialized in phrases of the Simple Object Access Protocol the use of Simple Object Access Protocol serialization. system. interval. Serialization. Formatter. To take benefit of Simple Object Access Protocol serialization, you have to encompass the SOAP namespace to your application. 3.3. XML serialization Public participants of an example of a category may be serialized into an XML circulation the use of XML serialization.

    • XML serialization speeds are lots slower than binary serialization speeds. Cross-platform guide is furnished SOAP serialization is similar to XML serialization in that the objects to be serialized are stored as XML. However, the similarity ends there. The classes used for SOAP serialization are in the System.Runtime.Serialization namespace, not the System.Xml.Serialization namespace used for XML serialization.

    • The runtime serialization classes (including the SoapFormatter and BinaryFormatter classes) use a completely different serialization mechanism than the XmlSerializer class.

    • The benefits of SOAP serialization are: Understanding SOAP Generates a fully SOAP- compliant envelope that can be processed by any system or service. Supports either objects that implement the ISerializable interface that controls their own serialization, or objects marked with the SerializableAttribute attribute. SOAP envelopes can be deserialized into a compatible set of objects.

    • You can serialize and restore private and public members of an object. SOAP serialization limits are as follows: Classes to be serialized must be marked with the SerializableAttribute attribute or implement an ISerializable interface to control their own serialization and deserialization. Understand only SOAP. Does not work with any XML schema the use of XML serialization.

    • XML serialization is text-based. XML serialization is simple to read. XML serialization is simple to edit. You can set a assets at the XmlAttribute and use XML serialization to serialize the assets.

    • 4. Custom serialization

      Use custom serialization to control instance type serialization and deserialization. Custom serialization can be implemented by implementing the ISerializable interface. The GetObjectData () method is declared by the ISerializable interface. To implement the ISerializable interface and demonstrate custom serialization, consider the following code.

      • [System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Struct, Inherited=false)]
      • public sealed class SerializableAttribute : Attribute


    • Data over wire (messaging). Data storage (database, hard drive). Remote procedure call, eg SOAP. Distribution of objects, especially in component-based software development such as COM and CORBA. Detection of changes in time-varying data. To use some of these features, you need to maintain architectural independence.

    • For example, to get the most out of your distribution, you need to ensure that computers running different hardware architectures can reconstruct serialized data streams, regardless of endianness. Therefore, an easier and faster way to copy the memory layout of a data structure directly does not work reliably on all architectures.

    • Serializing data structures in an architecture-independent format means avoiding problems with byte ordering, memory layout, or different ways of representing data structures in different programming languages. Unique to the serialization scheme, the encoding of the data is serial by definition, so to extract part of the serialized data structure, the entire object must be read and reconstructed end-to-end. It means that there is.

    • For many applications, this linearity is an advantage because you can use a simple and common I / O interface to maintain and propagate the state of the object. For applications that require higher performance, it may make sense to spend more effort dealing with more complex nonlinear memory configurations.

    • Even on a single computer, the primitive pointer object is too vulnerable to save. This is because the objects they point to can be reloaded elsewhere in memory. To address this, the serialization process involves a step called unwisling or pointer unwisling. In this step, direct pointer references are converted to references based on name or position. The deserialization process involves a reverse step called pointer swizzling.

    • Both serialization and deserialization can be controlled by high-level code (such as the Serialize function in Microsoft Foundation Classes), so running both simultaneously in high-level code 1) making a difference between objects. I can. It recognizes what is serialized and its previous copy, and 2) provides input for such recognition as follows. You don't actually have to make a previous copy because you can detect the differences on the fly, a technique called diff execution. This is useful when programming a user interface where the content is time-varying. Graphical objects can be created, deleted, modified, or configured without necessarily writing separate code to handle input events.

    • Disadvantage

    • Serialization eliminates the opacity of abstract data types because it can expose the details of private implementations. A simple implementation that serializes all data members can violate encapsulation.

    • Proprietary software publishers often keep the details of the serialization format of their programs trade secrets to discourage competitors from making compatible products. Some serialized data is intentionally obfuscated or encrypted.

    • Many institutions, such as archives and libraries, attempt to future proof their backup archives—in particular,database dumps—by storing them in some relatively humanreadable serialized format.

    • C and C Plus Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download


      In this instructional exercise, we covered serialization object steps, executed serialization and different sorts of serialization. These incorporate twofold serialization, XML serialization, SOAP serialization, and custom serialization. At long last, we close the article with a few guides to address something similar.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free