Open sandboxFocusImprove this doc

SR0016: PSerializable Type Already Has a Nested Serializer Type

Severity Error
Reported by PostSharp
Message Cannot apply [PSerializable] to type '<Type>' because it already contains a nested type named 'Serializer'.

Cause

[PSerializableAttribute] generates the serializer of a type as a nested class named Serializer. PostSharp reports SR0016, on the [PSerializable] type, when this type already contains a nested type of this name, whatever its kind and visibility.

In the following example, the [PSerializable] class Order contains a static class named Serializer that formats an order as CSV.

using System;
using System.IO;
using PostSharp.Serialization;

namespace Errors.SR0016_Error;

// Order contains a nested type named Serializer, where PostSharp would generate its own serializer.
[PSerializable]
public class Order
{
    public int Id { get; set; }

    public string? Product { get; set; }

    public static class Serializer
    {
        public static string ToCsv( Order order ) => $"{order.Id},{order.Product}";
    }
}

public static class Program
{
    public static void Main()
    {
        var formatter = new PortableFormatter();
        var stream = new MemoryStream();
        formatter.Serialize( new Order { Id = 7, Product = "Coffee" }, stream );
        stream.Position = 0;

        var order = (Order) formatter.Deserialize( stream );
        Console.WriteLine( Order.Serializer.ToCsv( order ) );
    }
}
error SR0016: SR0016_Error.cs(9,14): Cannot apply [PSerializable] to type 'Errors.SR0016_Error.Order' because it already contains a nested type named 'Serializer'.

Resolution

Rename the nested type, or move it out of the [PSerializable] type.

In the following example, the nested class is renamed CsvSerializer, and an Order is serialized and deserialized with PortableFormatter.

using System;
using System.IO;
using PostSharp.Serialization;

namespace Errors.SR0016_Fixed;

[PSerializable]
public class Order
{
    public int Id { get; set; }

    public string? Product { get; set; }

    // The nested type has another name, so PostSharp can add its Serializer type.
    public static class CsvSerializer
    {
        public static string ToCsv( Order order ) => $"{order.Id},{order.Product}";
    }
}

public static class Program
{
    public static void Main()
    {
        var formatter = new PortableFormatter();
        var stream = new MemoryStream();
        formatter.Serialize( new Order { Id = 7, Product = "Coffee" }, stream );
        stream.Position = 0;

        var order = (Order) formatter.Deserialize( stream );
        Console.WriteLine( Order.CsvSerializer.ToCsv( order ) );
    }
}
7,Coffee

See Also

Reference

PSerializableAttribute
PortableFormatter

Other Resources

Understanding Aspect Serialization