Partial Class Example, Partial Classes in ASP.Net 2.0

It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled.

Partial Classes:
There are several situations when splitting a class definition is desirable:
  1. When working on large projects, spreading a class over separate files enables multiple programmers to work on it at the same time.
  2. When working with automatically generated source, code can be added to the class without having to recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web service wrapper code, and so on. You can create code that uses these classes without having to modify the file created by Visual Studio.
  3. To split a class definition, use the partial keyword modifier.
public partial class Employee
{
public void DoWork()
{
}
}

public partial class Employee
{
public void GoToLunch()
{
}
}

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the namespace. All the parts must use the partial keyword. All the parts must be available at compile time to form the final type. All the parts must have the same accessibility, such as public, private, and so on.

If any part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the whole type is considered sealed. If any part declares a base type, then the whole type inherits that class.

All the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Parts can specify different base interfaces, and the final type implements all the interfaces listed by all the partial declarations. Any class, struct, or interface members declared in a partial definition are available to all the other parts. The final type is the combination of all the parts at compile time.

The partial modifier is not available on delegate or enumeration declarations.

The following are merged from all the partial-type definitions:
  • XML comments
  • interfaces
  • generic-type parameter attributes
  • class attributes
  • members
Tags: , , , , , , , , , , , , , , , , ,
Hot on Web:


About author