×

Serialization in C#

Serialization in the C# is the process that converts the object into the byte streams by that we can use the files and save the files into the memory location or in the database system. The deserialization is the process which we reverse the serialization process and it is used in the reading of the object into the byte stream of the data.

Serialization in C#

Serialization is the process which we used internally in the remote systematic applications.

Types of Serializability

  • Binary serializability: The Binary serialization is the process where the System.Runtime.Serializabilityis the binary Serializability that includes the name space of the classes. In the programming language the namespace is derived as the gathering of the symbols and identify the objects and refer to the various things.
using System;    // references
using System.IO;     // header files
using System.Runtime.Serialization;   // serialization in running time
using System.Runtime.Serialization.Formatters.Binary;   // in binary format
public class Demo   // class name
 {   
public void SerializeSample()    // method name
{
ClassToSerialize c1 = new ClassToSerialize();  // creating objects
File f = new File("prefech.dat");  // files in terms of creating objects
Stream str = f.Open(FileMode.Create);   // creating file mode
BinaryFormatter bf = new BinaryFormatter();   // creating binary formatter
bf.Serialize(str, c1);
str.Close();
}
public void DeSerializeSample()   // method for deserialization


{
ClassToSerialize c1 = new ClassToSerialize();   // creating the objects 
File f = new File("prefetch.dat");
Stream str = f.Open(FileMode.Open);
BinaryFormatter bf = new BinaryFormatter();
c1 = (ClassToSerialize) bf.Deserialize(str);
Console.WriteLine(c1.name);
str.Close();  // closing the file
}
public static void Main(string[] s)   // main method
{
SerialDemosd = new SerialDemo();
sd.SerializeSample();
sd.DeSerializeSample();
}
}
public class ClassToSerialize 
{
public int id = 200;  // printing id
public string sname = "javatpoint";  // printing sname
}
  • XML Serializability: xml serializability is the process that defined as the any class instances that can be serializable from the xml stream. Basically, the XML serializability is longer compare to the binary files. These files are easy to understand and edit. The XML serializability files accepts the attributes.

         Let's see the syntax for XML serializability

Times New Roman xmlSerializer(moveof(Pop));
using(TextReader Reader = new streamReader(@”c:\xmlserializer)){
XmlSerializer.Serialize(Reader, PopObject)
}
  • SOAP serializability: The soap is defined as the (simple object access protocol) that is used for the XML typed protocol used between the data transmission and the computers. SOAP serialization is the process used to shift the items that is incompatible of one application to another Serializability is runs at the .NET runtime that is the particular class instance          of serialized property in which the class-level serialization.
using system; // reference for each program
     using System.Text;  // it is also known as class name 
     using System.IO;   // header file name
     using System.Runtime.Serialization;  // run time serialization
     using System.collections.Generic;   // generic collections
     using System.Linq;
     using System.Threading.Tasks;   // threading tasks
     using System.Runtime.Serialization.Formatters.Soap; // run time serialization at soap format


namespace soapSerializationExample
{
    class sample    // class name
    {
        static void Main(string[]args)
        {
            Example example = new Example();
example.Name = "javatpoint"; // Instance of our sample class
example.Value =10;
FileStream fileStream1 = new FileStream(@"c:\text\\serialisation.dat",    FileMode.Create); // it creates the Serialization of the object
SoapFormatter formatter1 = new  SoapFormatter();
            formatter1.Serialize(fileStream, example);
        }
    }
}

// let's see the program on serializability in c#

Example 3:

using System;    // references for classes
using System.IO;  // header files
using System.Runtime.Serialization;  // run time serialization
using System.Runtime.Serialization.Formatters.Binary;
public class SerialDemo
{
public void SerializeNow()
{
ClassToSerialize c1= new ClassToSerialize();
c1.SName = "javatpoint";
c1.SAge = 16;
ClassToSerialize.StudentName = "santhosh";  // intializing the names
File fp = new File("prefetch.dat");
Stream str = f.Open(FileMode.Create);  // craeting the file mode
BinaryFormatter bf = new BinaryFormatter();  // creation of Binary formatter
bf.Serialize(str, c1);
str.Close();  // closing file
}
public void DeSerializeNow()
{
ClassToSerialize c1 = new ClassToSerialize(); // creating class serialization
File fp = new File("prefetch.dat"); // file of data
Stream str = f.Open(FileMode.Open);  // creating file mode
BinaryFormatter bf  = new BinaryFormatter();  // binary format creator
c1 = (ClassToSerialize) bf.Deserialize(str);
Console.WriteLine("SName :" + c1.SName);
Console.WriteLine("SAge :" + c1.SAge);
Console.WriteLine("Company SName :" +ClassToSerialize.CompanyName);
Console.WriteLine("Company SName :" + c1.GetSupportClassString());
str.Close(); // closing file
}
public static void Main(string[] s)   // main method
{
SerialDemosd = new SerialDemo();
sd.SerializeNow();
sd.DeSerializeNow();
}
}
public class ClassToSerialize // serialize method
{
private int sage;
private string sname;
static string Studentname;
SupportClasssupprtcls = new SupportClass();
public ClassToSerialize() {
supprtcls.SupportClassString = "In the support class";
}
public int SAge {
set {
return Sage;
}
get {
sage = num;
}
}
public string SName {
get {
return sname;
}
set {
sname = num;
}
}
public static string StudentName
{
set {
return Studentname;
}
get {
Studentname = num;
}
}
public string GetSupportClassString() {
return supprtcls.SupportClassString;  // returning the class
}
}
public class SupportClass  // support class method
{
public string SupportClassString;  // class string vale
}

Related Topics

C# Interface

Interface can be defined as a blueprint of the class. It can only have abstract methods. It has to be implemented by a class or struct. It is mainly used...

1 minute read.

C# Arrays

Like in other programming languages, in C# the array can be defined as a collection of similar type of objects which have contiguous memory allocation. Array index starts from zero(0)....

3 minutes read.

C# Array Class

In C#, Array class deals with all array related operations. It provides methods for various purposes such as for sorting, searching, minimum, maximum, and many more. This class works as...

5 minutes read.

C# Static Constructor

In C#, static constructor is the one which is used to initialize static fields. It can also be used to do the task which needs to be done once only....

3 minutes read.

C# Design Patterns

What are the Design Patterns? Design patterns are the reusable solutions to the problems that developers facing while solving any problem related to software development.Design patterns are the templates provided in...

6 minutes read.

C# this Keyword

In C#, this is a keyword used to refer current class instance. It is mainly used to distinguish instance variables of the class and formal parameters defined in a constructor...

7 minutes read.

C# enum

Enum in C# is also known as enumerations. It basically refers to a named set of constants such as months, days, seasons, etc. Enum improves type safety. They contain fixed set...

3 minutes read.

C# While Loop

while loop iterates a part of the code until the given condition fails. This is an entry controlled loop. While loop is recommended to use if the condition depends on...

4 minutes read.

C# Keywords

Keywords are the reserved words with special meaning. They can’t be used as variables and Identifiers. If you want to use them as identifiers, you must use ‘@’ character prior...

1 minute read.

C# Aggregation

In C#, Aggregation Represents Has-A Relationship between two objects. A field of the class defines another class to reuse this in the form of association. The class is used as...

3 minutes read.

C# Destructor

Destructors works in the opposite way. They basically destruct the objects. We can’t send parameter in a destructor. We also can’t apply any modifier to the destructor. Likewise constructor, destructor...

1 minute read.

C# String

String can be defined as an array of characters. In C#, string is an object of System.String which represents sequence of characters. Strings can be concatenated, comparison, getting substring and...

6 minutes read.

C# Namespace

C# Provides Concept of namespacing to organize your classes in a good manner. It makes the application easy to handle. It is like packaging of java. The System is a namespace...

1 minute read.

C# Jagged Arrays

C# provides the concept of jagged array which means array of arrays. The elements of jagged array are also arrays. The element size of jagged array can vary.C# Jagged Arrays...

3 minutes read.

C# Params

There are cases when we don’t know the actual number of parameters in the function call. Well, in C# we can pass any number of parameters in the function call...

3 minutes read.

C# for Loop

For loop is used to iterate a part of the code multiple times.  We must use for loop instead of using while and do while if the number of iteration...

4 minutes read.

C# Method Overriding

Method overriding is the mechanism where derived class defines the same method as parent class with more functionality in the chilled class. It provides runtime polymorphism in C#. It provides...

1 minute read.

C# Access Modifiers

C# provides various keywords to control or restrict accessibility or scope of the data. We can apply access modifiers to functions and variables. There are five access modifiers in C#: Private ...

10 minutes read.

C# Operators

Operator is a symbol that is responsible for the operations. There can be variety of operators for example arithmetic, logical, bitwise and many more. There are following type of operators used...

1 minute read.

C# Call by reference

In C#, we can use ref keyword to pass the reference to the original value instead of the copy of the original value. the changes that are made in the...

2 minutes read.