The following article provides an outline on C# Serialization. The process by which the object instance is converted into a data stream is called serialization and the state of the object instance is converted into data stream because it can be transported across different networks made to be persisted in a location of storage. This serves as an advantage of serialization to transmit the converted data stream across different networks in a format compatible on cross platforms and saves the converted stream data into a medium of storage in a persistent or non-persistent object state so that the same copy can be created in the later time.
Steps of C# Serialization Object
Given below are the steps of C# Serialization Object:
- A stream object is created.
- A BinaryFormatter object is created.
- Serialize( ) method is called.
Working of C# Serialization
- Whenever we are working with applications, it is necessary to store the data in a medium which is either persistent or non-persistent so that the same data can be retrieved later. This can be achieved by using the concept of Serialization.
- The process of converting an instance of the object into a byte stream moving the state of the object into the memory or database of the file is called Serialization.
- Serialization is essential to transmit the object across the network to cross platforms in a compatible format.
- A clone of an object can also be created using Serialization.
- Runtime.Serialization namespace must be included in the program to make use of Serialization in C#.
- [ Serializable ] attribute is used to make a class Serializable in C#.
An example class to demonstrate [ Serializable ] class:
Code:
[Serializable] public class Check { public int code; public string name; }
- Similarly, if we want to make any members of the class non-serializable, we can use [ NonSerialized() ] attribute.
Consider the example class below to demonstrate [ NonSerialized() ] attribute:
Code:
[Serializable] public class Check { public int code; public string name; [NonSerialized()] Public double price; }
- The following types of serialization are supported by C#.
Given below are the types of serialization that are supported by C#:
1. Binary Serialization
- The fastest of all the techniques of serialization is Binary serialization.
- An object can be serialized to a binary stream using Binary Serialization.
- The identity of the object is preserved while the object is serialized to an output stream using binary serialization.
- System. Runtime. Serilaization. Formatters. Binary namespace must be included in the program to make use of binary serialization.
2. SOAP Serialization
- Simple Object Access Protocol is the abbreviation of SOAP.
- We use Simple Object Access Protocol Serialization if we have to transfer the objects from one application to other application which are made of architectures that are heterogeneous.
- Portability is the main benefit of using Simple Object Access Protocol Serialization.
- An object can be serialized in the form of Simple Object Access Protocol using Simple Object Access Protocol Serialization.
- System. Runtime. Serilaization. Formatters. Soap namespace must be included in the program to make use of Simple Object Access Protocol serialization.
3. XML Serialization
- The public members of the instance of a class can be serialized into an XML stream using XML Serialization.
- The speed of XML Serialization is very slower when compared to the speed of binary Serialization.
- Cross-platform support is provided by using XML Serialization.
- XML Serialization is based on text.
- XML Serialization is easily readable.
- XML Serialization is easily editable.
- A property can be set on XmlAttribute to serialize the property using XML Serialization.
Consider the code below to demonstrate the use of XmlAttribute:
Code:
[XmlAttribute("Name")] public string Name { get { return Name; } set { Name = val; } }
- We make use of XmlSerializer to serialize an object using XML Serialization.
Consider the code below to demonstrate the use of XmlSerializer:
Code:
XmlSerializer Serializer = new XmlSerializer(typeof(Prod)); using (TextWriter Writer = new StreamWriter(@"C:\Prod.xml")) { xmlSerializer.Serialize(Writer, prodObject); }
4. Custom Serialization
- In order to control the serialization and deserialization of a type of instance, we make use of Custom Serialization.
- Custom Serialization can be implemented by the implementation of ISerializable interface.
- GetObjectData() method is declared by ISerializable interface.
Consider the code below to demonstrate custom Serialization by implementing the ISerializable interface:
Code:
[Serializable] public class Prod : ISerializable { public void GetObjectData(SerializationInfo information, StreamingContext cont) { //Usual code } }
Example
Given below is the example of C# Serialization:
C# program to demonstrate the concept of Serialization.
Code:
using System; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; //a namespace called demo is created namespace Demo { //Serializable attribute is declared [Serializable] //a class check is defined which will be used for serialization class Check { public int identity; public String nam; static void Main(string[] args) { //an object of the check class is created to serialize it to the file Example.txt Check ob = new Check(); ob.identity = 10; ob.nam = "Shobha"; //a file stream is created IFormatter format = new BinaryFormatter(); Stream stream1 = new FileStream(@"E:\Example.txt",FileMode.Create,FileAccess.Write); //serialization of the object of the class check is done format.Serialize(stream1, ob); stream1.Close(); //a file stream is created stream1 = new FileStream(@"E:\Example.txt",FileMode.Open,FileAccess.Read); //the object of the class check is deserialized Check ob1 = (Check)format.Deserialize(stream1); //the data is written to the console Console.WriteLine(ob1.identity); Console.WriteLine(ob1.nam); Console.ReadKey(); } } }
Output:
In the above program, a namespace called demo is defined. Then a Serializable attribute is defined. A class check is defined to demonstrate the concept of serialization using this class. Two properties identity and nam are defined in the class to which the values 10 and Shobha are assigned respectively. Then an object of the check class is created to serialize it to the file Example.txt. Then a formatter class is defined to convert the object of the class check to a binary stream.
Then a file stream object is created to open the file Example.txt in write mode to write the values of the properties identity and nam into it. Then serialize method is used to transfer the binary data into the text file. Finally, We use deserialize method to deserialize the contents of the text file Example.txt and the data is written to the console as shown in the output snapshot above.
The above is the detailed content of C# Serialization. For more information, please follow other related articles on the PHP Chinese website!

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

C# is not always tied to .NET. 1) C# can run in the Mono runtime environment and is suitable for Linux and macOS. 2) In the Unity game engine, C# is used for scripting and does not rely on the .NET framework. 3) C# can also be used for embedded system development, such as .NETMicroFramework.

C# plays a core role in the .NET ecosystem and is the preferred language for developers. 1) C# provides efficient and easy-to-use programming methods, combining the advantages of C, C and Java. 2) Execute through .NET runtime (CLR) to ensure efficient cross-platform operation. 3) C# supports basic to advanced usage, such as LINQ and asynchronous programming. 4) Optimization and best practices include using StringBuilder and asynchronous programming to improve performance and maintainability.

C# is a programming language released by Microsoft in 2000, aiming to combine the power of C and the simplicity of Java. 1.C# is a type-safe, object-oriented programming language that supports encapsulation, inheritance and polymorphism. 2. The compilation process of C# converts the code into an intermediate language (IL), and then compiles it into machine code execution in the .NET runtime environment (CLR). 3. The basic usage of C# includes variable declarations, control flows and function definitions, while advanced usages cover asynchronous programming, LINQ and delegates, etc. 4. Common errors include type mismatch and null reference exceptions, which can be debugged through debugger, exception handling and logging. 5. Performance optimization suggestions include the use of LINQ, asynchronous programming, and improving code readability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
