Pages

Friday 11 January 2013

Partial Class, Interface or Struct in C Sharp with example

Partial class, interface and structure was introduced in C# 2.0. Now it is possible to split the definition of an class, interface and structure over more than one source files. Moreover the other parts of the class, struct, or interface should be defined in the same namespace or assembly. All the parts must have the partial keyword and same access modifier like as public, private, and so on. For more about partial method refer the article Partial Methods in C Sharp with example.

Why Partial Class, Interface or Struct?

  1. Allow more than one developers to work simultaneously on the same class, struct or interface.
  2. Partial class are particularly helpful for customizing auto generated code by the IDE. Whenever the IDE generate the code then tool may define some partial class, interface, methods and further customization of partial class, interface is done by the developers without messing with the system generated code.

Key Points about Partial Class, Interface or Struct

  1. During code compilation, all the parts should be available to form the final class, interface or struct.
  2. Any member declared in the one part will be available to all other parts.
  3. If any part has Inheritance, then it applies to the entire class.
  4. Different parts of a class or struct may inherit from different interfaces.
  5. If any part is declared abstract, then the whole class, interface or struct is considered abstract.
  6. If any part is declared sealed, then the whole whole class, interface or struct is considered sealed.

Auto-Generated Partial Class in Asp.Net by IDE

When ever you add an Asp.Net web from or web page to your web application or website than visual studio automatically added a partial class to your's page code behind. This code behind class is Inherited by the ASPX page.
 public partial class Default : System.Web.UI.Page
{
 protected void Page_Load(object sender, EventArgs e)
 {
 // your's code
 }
} 

Partial Class, Interface or Struct Example

 class MyNamespace
{
 partial class Example
 {
 void Test() { //write your code }
 }
 partial class Example
 {
 void Test2() { //write your code }
 }
} 
 partial interface IExample
{
 void ITest();
}
 partial interface IExample
{
 void ITest2();
} 
 partial struct SExample
{
 void STest() 
{ 
//write your code 
}
}
 partial struct SExample
{ 
void STest2() 
{ 
//write your code 
}
} 

Note

  1. The partial modifier is not available for delegate or enum.

No comments:

Post a Comment