Search code examples
c#class-design

Are partial methods considered harmful?


In C# 3.0 Microsoft introduced support for something called partial methods.

Do you use them? Can you describe how and why?

Do you consider the use of partial methods good programming practice, or not?


Solution

  • Partial methods are primarily useful for extension of the behaviour of tool generated code without cost in either runtime evaluation or user visible code where such extensibility is not used.

    As such their use is sensible and to be encouraged where it is necessary, but such occasions will be relatively uncommon for most users (who are not writing tools to generate code). If you are writing such a tool then consideration should be given to where people may which to interact with the flow of your generated code, and whether such usage cannot be handled easily through event like mechanisms while achieving your intended performance and usability goals. Events are inherently multicast and such structure may be inherently against the intended design of the API. Alternatively a complex return value, or interaction with ref/out parameters might be necessary, finally the extension may be complex/fragile despite its utility and as such only the partial class implementer may be in a position to adequately handle this. All these reasons have their niche, if not being common and partial methods can effectively solve them.

    Consumers implementing partial methods should use them as the tool generated code dictates (if an extension point is supplied and you need it, use it). To avoid doing this because one feels that the feature is confusing would be poor use of the language and API since this is clearly the intended extension point.