Skip to content

Partial properties & indexers C# 13.0code generation

Allow properties and indexers to be partially defined like partial methods.

C# 13 allows properties and indexers to be partially defined like partial methods C# 3.0 in that the basic definition can be defined and then implemented elsewhere. This is useful when the property implementation might be code-generated in a different file.

Code

C#
partial class PostSerializer
{
    public partial int BufferSize { get; set; }
}

partial class PostSerializer
{
    const int minBufferSize = 1024;
    private int bufferSize;

    public partial int BufferSize
    {
      get => bufferSize < minBufferSize ? minBufferSize : bufferSize;
      set => bufferSize = value;
    }
}
C#
partial class PostSerializer
{
    private int bufferSize;

    private partial int GetBufferSize();

    public int BufferSize
    {
        get => GetBufferSize();
        set => bufferSize = value;
    }
}

partial class PostSerializer
{
    const int minBufferSize = 1024;

    private partial int GetBufferSize()
        => bufferSize < minBufferSize ? minBufferSize : bufferSize;
}

Notes

  • Accessor modifiers must match between the partial definitions.
  • Doc comments will be taken from the implementation if present, otherwise they will fall back to the partial definition.

More information