Thursday, October 7, 2010

Partial Class

Visual Studio .NET 2005, ASP.NET 2.0, shipped with a lesser-known functionality called a “Partial Class”. A Partial class is a class defined in 2 or more files. Each source file contains a section of the class which will combine when the application is compiled.

In previous versions of Visual Studio classes are confined to a single file. It was not possible to split up a single class into multiple files. In order to split up a class we have to use the keyword “Partial”. The purpose of the Partial Class is to allow more than one programmer to write code for the same class, at the same time.


In the above example, the Employee class is split into 2 parts. The first part defines the GetName() method, and the second part defines the GetAge() method. When you compile this program both parts will be combined and compiled.

The important point to remember is both sections use the keyword Partial and the public access modifier.

Points to considered on creating Partial Class

  • All the parts must use the partial keyword.
  • During compile time, all the parts should be available to form the final class.
  • All the parts should have the same access modifiers. – Public, Private, Protected and etc.,
  • Any member declared in the partial class is available to all other parts.
  • If any part is abstract, the entire class is abstract
  • If any part is sealed, then entire class is sealed.
  • If any part has Inheritance, then it applies to the entire class.
  • We can create the Partial Structs, Interfaces and methods in the same way as we create partial classes.
  • Different parts of the partial calls can inherit from different interfaces.

In the above example two parts are declared as public. In the following example we will create one part as abstract.


If you create an object for the Employee class, you will get the following error:

“Cannot create an instance of the abstract class or interface Examples.Employee”.

This is because the second part is declared as abstract, so the whole class became abstract. Hence you cannot create an object.

We can create nested classes as partial class; even when the main class is not partial.

Important Points in Partial Method

  • Partial method declarations must begin with partial keyword.
  • The return type of the partial class should be void
  • Partial methods cannot have the out parameter, but can have the ref parameter.
  • Partial methods can be private but they cannot be virtual.
  • Partial classes cannot be extern.

No comments:

Post a Comment