Saturday, February 27, 2016

C Sharp : Partial Class, Interface or Struct in C Sharp

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.
  1. public partial class Default : System.Web.UI.Page
  2. {
  3. protected void Page_Load(object sender, EventArgs e)
  4. {
  5. // your's code
  6. }
  7. }

Partial Class, Interface or Struct Example

  1. class MyNamespace
  2. {
  3. partial class Example
  4. {
  5. void Test() { //write your code }
  6. }
  7. partial class Example
  8. {
  9. void Test2() { //write your code }
  10. }
  11. }
  1. partial interface IExample
  2. {
  3. void ITest();
  4. }
  5. partial interface IExample
  6. {
  7. void ITest2();
  8. }
  1. partial struct SExample
  2. {
  3. void STest()
  4. {
  5. //write your code
  6. }
  7. }
  8. partial struct SExample
  9. {
  10. void STest2()
  11. {
  12. //write your code
  13. }
  14. }

Note

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

No comments:

Post a Comment