Partial classes and methods in C#

Partial classes, structs and interfaces

Partial classes, structs or even interfaces can be declared in C#. This mechanism allows us to split a class, struct or interface definition across multiple files which gives us some interesting possibilities.

For example, let’s same you reference a web service and you’ve generated a class like the following (I’ve removed extraneous base classes etc.)

public partial class Person
{
   private string string FirstNameField;
   private string string LastNameField;

   public string FirstName
   {
      get { return this.FirstNameField; }
      set
      {
         if((this.FirstNameField.Equals(value) != true))
         {
            this.FirstNameField = value;
            this.RaisePropertyChanged("FirstName");
         }
      }
   }

   public string LastName
   {
      get { return this.LastNameField; }
      set
      {
         if((this.LastNameField.Equals(value) != true))
         {
            this.LastNameField = value;
            this.RaisePropertyChanged("LastName");
         }
      }
   }
}

By default svcutil.exe will create the class as a partial. This allows us to now define an addition to the class that implements more functionality which can be run locally and will remain when/if we need to regenerate the proxies class above. We simply create another file (by convention this would be the .partial.cs, so in this case Person.partial.cs but of course this isn’t a requirement for partials to work).

public partial class Person
{
    public string FullName
    {
       get { return String.Format("{0} {1}", FirstName, LastName); }
    }
}

Partial Methods

Partial methods are methods whose signature can exist in one partial type but it implementation may defined in another. For example

public partial class Project
{
   partial void Run();
}

// in another file we might have
public partial class Project
{
   partial void Run()
   {
      Console.WriteLine("Running");
   }
}

A partial method must have the following:

  • The signature for the method must match in the partial type
  • The method can only return void
  • Partial methods are implicitly private and no access modifiers are allowed (even private is not allowed)

One of the key things about a partial method is the even if there’s no implementation of the method the code will still compile successfully and run. So you can use a partial method as a place holder for possible implementation at some later time if you wished and the code would still work. If no implementation exists for Run (in the above example) any calls to the Run method will be removed.