Friday, 14 August 2015

Partial in C# - Partial class and Partial methods

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.

Creating partial class :


  • All the part of class spread across different files must use the partial keyword.
  • All part of class must have same access modifiers.
  • If any of the part is declared abstract, then entire type is considered abstract.
  • If any of the part is declared sealed, then entire type is considered sealed.
  • If any of part inherit a class , then entire type inherit that class.
  • Different part of partial class can't specify different base class.
  • Different part of partial class can specify different base interface.
  • Any member declared in a partial definition are available to all the other parts of the partial class.

Partial Method :


  • A partial  class and structure can contain partial method.
  • Implementation of partial method is optional, If we compile it without body, it will compile.actually compiler ignore partial method declaration and its call until it's body is defined.
  • Partial method is private by default.partial method can't have any modifier like access modifiers, static, abstract, virtual etc.
  • Without declaration of partial method you can't provide definition for partial method, it will give compile time error.
  • A partial method return type is must be void, including any other return type is a compile time error.
  • signature of declaration and definition of partial method must be same.
  • Partial method can be implemented only once otherwise compile time error.


class Program
    {
        public static void Main()
        {

            test obj ;
            obj.hello();

            Console.Read();          

        }
    }  
    public partial struct test
    {
        partial void partialMethod();
        public void hello()
        {
            partialMethod();
        }
    }
    public partial struct test
    {
        partial void partialMethod()
        {
            Console.WriteLine("Hello");
        }      
    }

No comments:

Post a Comment