Partial Class vs Extension Method

You can use extension methods on a NULL instance but not instance methods (of partial classes or otherwise). This is a consequence of extension methods actually being static.


Some of differences that will determine whether you want to use a Partial Class or an Extension Method are

Partial Class

  • Only works against classes in the same project/assembly
  • Target class has to be marked as partial
  • Has access to the Target class' fields and protected members
  • Target must be a class implementation

Extension Method

  • Can be applied against classes in other assembles
  • Must be static, has access to only the Target classes public members
  • Target of extension can be a concrete type, or an abstract type or interface

Partial classes should be used in code generation scenarios.

Since the generated file might get overwritten at any time, one uses partial classes to write into the non-generated file.

Additionally, partials will only work if they are part of the same assembly - they cannot cross assembly boundaries.

If these are not your constraints, you can and should use extension methods - of course, after considering other possibilities such as inheritance and composition for suitability.