C# Tutorial - Even More on Classes

posted Jun 26, 2011, 11:15 PM by magic stone

C# allows a single class to be split across several files, through the use of the keyword partial. Partial classes do not make any logical difference to the compiler, as during compile time, it simply groups all of the various parts of the partial class and treats them as a single entity.

Why use Partial Classes?

Partial classes allow for a clean separation of business logic (implementation code) and the user interface (designer code). The UI code can be hidden away from the developer by the IDE, as the developer would access this code through the properties window.

Partial classes can also allow large classes to be separated into smaller manageable sections. The benefit of this is twofold; firstly the code becomes less cumbersome to navigate and second, multiple developers can work on a single class at the same time without the need for later merging of files within a source control application.

On top of this, by naming the partial class files with appropriate names, debugging of code becomes easier because you can jump quicker to an area of functionality.

Naming Files

Naming files containing a partial class becomes an important issue. Names should include the name of the class that is being defined as well as an indication of which aspects of the class are being defined in that file.

Visual C# Express splits any control or form into two files using the partial class implementation when you add one to your project. For example, when you add a new Form to your project, the code that you edit is called Form1.cs, and the code that is created by the IDE is called Form1.Designer.cs. Both files contain the same class, but use the partial keyword.

If for instance you create a class that has a lot of properties, then you may name the file myClass.Properties.cs wheremyClass is the name of the class within the file.

A Word of Warning

If a class ends up being split over many files, it may be time to stop and rethink whether the class would benefit from refactoring and taking advantage of some inheritance.

Coding Partial Classes

As an example to demonstrate the use of partial classes, we will break the Person class into private and public areas.

Anything public can be held in one file.

Person.cs
public partial class Person
{
  // Constructor
  public Person()
  {
  }

  // Methods
  public void setSurname( string aSurname )
  {
    _surname = aSurname;
  }

  public string getSurname()
  {
    return _surname;
  }
}

Anything private can be held in another file.

Person.Private.cs
partial class Person
{
  // Attributes
  private string _forename;
  private string _surname;
  private string _address;
  private int _age;
  private bool _gender;
  private string _dateOfBirth;
  private int _telephoneNumber;
  private int _NINumber;
}

Note

Both parts of the class must reside in the same namespace.

Comments