ISerializable Interface
Namespace: System.Runtime.Serialization
Assembly: System.Runtime.Serialization.dll
Provides data for the SerializationCallback attribute and defines the interface that custom serialization procedures must implement.
Members
| Name | Description |
|---|---|
| GetObjectData | When implemented in a derived class, sets the SerializationInfo with information about the serializable object. |
Remarks
The ISerializable interface is used to control the serialization process for types that require custom serialization logic. This is typically necessary when the default serialization mechanism is insufficient or when you need to handle specific aspects of object state during serialization and deserialization.
Types that implement ISerializable must also have a constructor with the following signature:
protected MyClass(SerializationInfo info, StreamingContext context);
This constructor is invoked during deserialization to reconstruct the object's state from the provided SerializationInfo.
Requirements
- Namespace:
System.Runtime.Serialization- Assembly:
System.Runtime.Serialization.dll
See Also
Example
Here's a basic example demonstrating how to implement ISerializable:
using System;
using System.Runtime.Serialization;
[Serializable]
public class CustomData : ISerializable
{
public string Name { get; set; }
public int Value { get; set; }
// Constructor for deserialization
protected CustomData(SerializationInfo info, StreamingContext context)
{
this.Name = info.GetString("Name");
this.Value = info.GetInt32("Value");
}
// Implement ISerializable.GetObjectData
public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("Name", this.Name);
info.AddValue("Value", this.Value);
}
// Optional: Default constructor
public CustomData() { }
public override string ToString()
{
return $"Name: {Name}, Value: {Value}";
}
}
// Usage example (typically within a serialization context)
// BinaryFormatter formatter = new BinaryFormatter();
// using (MemoryStream stream = new MemoryStream())
// {
// CustomData originalData = new CustomData { Name = "Example", Value = 123 };
// formatter.Serialize(stream, originalData);
// stream.Position = 0;
// CustomData deserializedData = (CustomData)formatter.Deserialize(stream);
// Console.WriteLine(deserializedData.ToString());
// }