Search code examples
c#.netpartial-methods

Why you need partial methods in c#? Can events be used to achieve the same goal?


I was reading the book "Apress Pro LINQ: Language Integrated Query in C#" and I came across partial methods, but I really don't understand what is the need for them.

I think the examples in the book (properties before and after change) can be implemented using events. So any explanation?


Solution

  • Yes, you could achieve a similar effect with events as you can with partial methods. Partial methods are really just a way of letting code generators, primarily designers, to generate hooks for the non-generated code. Events could fill this role.

    However there are advantages to partial methods over events in particular

    • Partial method calls are completely removed from the generated IL if there is no implementation. This cannot be done with events.
    • The design of partial methods is to solve the problem where there is 1 provider of the hook and 1 consumer. Events are meant to model 1 provider with N consumers and have the overhead which comes with such a design
    • There is no issue of ordering (who goes first). With events you need to ensure the code which subscribes to the event runs before the designer generated code that raises the event. This is not always possible if say the designer generates a constructor. Partial methods have no such issue.