Thursday, June 19, 2008

What is Partial Class in C#

What is Partial Class in C#
With C# 2.0 it is possible to split definition of classes, interfaces and structures over more than one files.Each source file contains a section of the class definition, and all parts are combined when the application is compiled.There are several situations when splitting a class definition is desirable:

  • More than one developer can simultaneously write the code for the class
  • You can easily write your code for a VS.NET generated class. This will allow you to write the code of your own need without messing with the system generated code.
  • To split a class definition, use the partial keyword modifier.


Conditions:



  • Using the partial keyword indicates that other parts of the class, struct, or interface can be defined within the namespace.
  • All the parts must use the partial keyword (Class , Struct and interface).
  • All the parts must have the same accessibility, such as public, private, and so on.



  1. If any of the parts are declared abstract, then the entire type is considered abstract.
  2. If any of the parts are declared sealed, then the entire type is considered sealed.
  3. If any of the parts declare a base type, then the entire type inherits that class.
Not Applicable


  • The partial modifier is not available on delegate or enumeration declarations.
  • Partial definitions cannot span multiple modules.

  • Example





    File 1:


    public partial class myPartialClass

    {
    public myPartialClass()
    {
    Console.WriteLine(" I am in partial class in other Partial.cs");

    }

    public myPartialClass(string pString)
    {
    Console.WriteLine("I am in a partial class in Partial.cs. The parmeter passed is: " + pString);
    }

    public void doSomethingElse()
    {
    Console.WriteLine(" I am in Partial.cs ");
    }
    }




    File 2:


    public partial class myPartialClass
    {
    public myPartialClass()
    {
    Console.WriteLine(" I am in a partial class in Program.cs");t
    }

    public void doSomething()
    {
    Console.WriteLine(" I am in Progam.cs ");
    }
    }

    class TestProgram
    {
    static void Main(string[] args)
    {
    myPartialClass myCompleteObject = new myPartialClass();
    myCompleteObject.doSomething();
    myCompleteObject.doSomethingElse();
    Console.ReadLine();
    }
    }

    No comments: