Skip to content

Serialisation constructor

Context: If your custom exception may be serialized (e.g., across AppDomains, in remoting, or in logs), you must implement a special constructor that takes SerializationInfo and StreamingContext. This constructor is called during deserialization and should pass the parameters to the base constructor. Also apply the [Serializable] attribute.

using System;
using System.Runtime.Serialization;
[Serializable]
public class SerializableException : Exception
{
public SerializableException() { }
public SerializableException(string message) : base(message) { }
public SerializableException(string message, Exception inner) : base(message, inner) { }
// Serialisation constructor
protected SerializableException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
class Program
{
static void Main()
{
var ex = new SerializableException("Test");
Console.WriteLine(ex.Message);
}
}
Terminal window
dotnet run
Test
  • The serialisation constructor must be protected or public.
  • It should always call base(info, context).
  • Required for exceptions that cross boundaries (e.g., in microservices, WCF).

Distributed systems – Custom exceptions in a library used by multiple services need serialisation to preserve error details.
See .NET docs on serialisation constructors.