How to use serialization in C#
By FoxLearn 1/7/2025 2:51:46 AM 89
The reverse process, deserialization, reconstructs the object from this byte stream. Serialization is essential for passing objects over a network or between application domains, and it can also be used to create object clones.
However, serialization has a performance cost due to the overhead of converting objects to and from byte streams. In .NET, serialization is handled through the `System.Runtime.Serialization` namespace.
You can make a class serializable by applying the [Serializable]
attribute.
[Serializable] public class Employee { public int employeeId; public string employeeName; }
If you want to prevent specific members of a class from being serialized, you can use the [NonSerialized]
attribute.
For example:
[Serializable] public class Employee { public int employeeId; public string employeeName; [NonSerialized] public double employeeSalary; }
The .NET framework supports different types of serialization, including:
- Binary Serialization
- SOAP Serialization
- XML Serialization
- Custom Serialization
Binary serialization
Binary serialization is the fastest serialization method, enabling you to serialize an object into a binary stream. This technique preserves the object's identity, meaning its type information is retained during the serialization process. When binary serialization is used, the entire object is saved. To implement binary serialization, you need to include the System.Runtime.Serialization.Formatters.Binary
namespace in your project.
SOAP serialization
SOAP (Simple Object Access Protocol) serialization is ideal for transferring objects between applications with different architectures. The key advantage of SOAP serialization is its portability. It allows objects to be serialized in the SOAP format, which is widely supported for communication between heterogeneous systems. To use SOAP serialization, you need to include the System.Runtime.Serialization.Formatters.Soap
namespace in your application. Similar to XML serialization, objects serialized with SOAP are stored in XML format.
XML Serialization
XML serialization is a technique used to convert the public members of an object into an XML stream. While XML serialization is slower compared to Binary serialization, its key advantage is cross-platform compatibility. Additionally, being text-based, XML files are human-readable and can be easily edited. To enable a property to be serialized, you can use the XmlAttribute
to annotate it.
For example, how to use XmlAttribute
on a property:
[XmlAttribute("productCategory")] public string ProductCategory { get { return productCategory; } set { productCategory = value; } }
To serialize and deserialize an object with XML serialization, you can use the XmlSerializer
.
For example, how to serialize an object into XML format using XmlSerializer
:
XmlSerializer xmlSerializer = new XmlSerializer(typeof(Product)); using (TextWriter textWriter = new StreamWriter(@"C:\Product.xml")) { xmlSerializer.Serialize(textWriter, productObject); }
This code serializes the productObject
into an XML file named Product.xml
located at C:\
.
Custom serialization
Custom serialization allows you to define exactly how an object of a class should be serialized and deserialized. To implement custom serialization, you can use the ISerializable
interface, which requires you to implement the GetObjectData()
method.
For example, how to implement custom serialization by using the ISerializable
interface:
[Serializable] public class Order : ISerializable { public int OrderId { get; set; } public string OrderDescription { get; set; } // Implementing the GetObjectData method for custom serialization public void GetObjectData(SerializationInfo info, StreamingContext context) { // Add the object's data to the SerializationInfo object info.AddValue("OrderId", OrderId); info.AddValue("OrderDescription", OrderDescription); } // Constructor for deserialization protected Order(SerializationInfo info, StreamingContext context) { OrderId = info.GetInt32("OrderId"); OrderDescription = info.GetString("OrderDescription"); } }
In this example, the Order
class implements the ISerializable
interface and customizes the serialization process by overriding the GetObjectData()
method. The Order
class also provides a special constructor for deserialization, which is required when implementing custom serialization.
- How to fix 'Failure sending mail' in C#
- How to Parse a Comma-Separated String from App.config in C#
- How to convert a dictionary to a list in C#
- How to retrieve the Executable Path in C#
- How to validate an IP address in C#
- How to retrieve the Downloads Directory Path in C#
- C# Tutorial
- Dictionary with multiple values per key in C#