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
- Partial methods must be private and may not have return types or
out
parameters - C# 9.0 extends partial methods to remove these restrictions
event
is still a useful extensibility model but Lapsed listeners can cause memory leaks