Partial Class Constructors

C# does support the feature of partial methods. These allow a partial class definition to forward declare a method that another part of the partial class can then optionally define.

Partial methods have some restrictions:

  • they MUST be of void type (no return)
  • they CANNOT accept out parameters, they can however accept ref parameters
  • they CANNOT be virtual or extern and CANNOT override or overwrite another method (via “new” keyword)

Partial methods are implicitly sealed and private.

It is not, however, possible, to have two different portions of a partial class implement the same partial method. Generally partial methods are used in code-generated partial classes as a way of allowing the non-generated part of extend or customize the behavior of the portion that is generated (or sometimes vice versa). If a partial method is declared but not implemented in any class part, the compiler will automatically eliminate any calls to it.

Here’s a code sample:

 public partial class PartialTestClass
 {
     partial void DoSomething();

     public PartialTestClass() { DoSomething(); }
 }

 public partial class PartialTestClass
 {
     partial void DoSomething()  { /* code here */ }
 }

Leave a Comment