Skip to content

Partial methods C# 3.0code generation

Declare an method signature in a partial class that can be implemented elsewhere.

Partial types C# 2.0 could not offer method stubs for a developer to override. Instead they needed to rely on events even when operations are private.

C# 3.0 allows partial classes to contain method stubs that have no body. Then either the partial method:

  • is not implemented and all calls to it are discarded by the compiler
  • is implemented and all calls to it go to that implementation

Code

C#
partial class PostSerializer
{
    partial void OnSerializing(Post post);
    partial void OnSerialized(Post post);

    public void Serialize(Post post, StreamWriter writer)
    {
        OnSerializing(post); // Compiler will remove as not implemented
        writer.Write(JsonSerializer.Serialize(post));
        OnSerialized(post);
    }
}

partial class PostSerializer
{
    partial void OnSerialized(Post post)
    {
        Logger.Log("Post " + post.Id + " serialized");
    }
}
C#
partial class PostSerializer
{
    delegate void PostEvent(Post p);
    event PostEvent OnSerializing = delegate { };
    event PostEvent OnSerialized = delegate { };

    public void Serialize(Post post, StreamWriter writer)
    {
        if (OnSerializing != null)
            OnSerializing(post);
        writer.Write(JsonSerializer.Serialize(post));
        if (OnSerialized != null)
            OnSerialized(post);
    }
}

partial class PostSerializer
{
    public PostSerializer()
    {
        OnSerialized = LogSerialized;
    }

    void LogSerialized(Post post)
    {
        Logger.Log("Post " + post.Id + " serialized");
    }
}

Notes

More information