Partial Classes and Partial Methods

By using Partial keyword we can partly devides our class,Struct, Interface into two or more files. Later when the application gets compiled all the files gets combined.

Splitting application code into several files is helpful,
  • When there is a large project development, we can devide our class into several different files so that it enables multiple programmers to work simultaneously on that class.
The best example of partial class is when we add new page in our web application or windows application in dot net, we can see 2 files gets added for our page/form.
For windows application, we have one Form1.cs file and another one is Form1.Designer.cs and if you check code behind of these files, you can see partial class defined there. In Form1.Designer.cs, we have definition of all controls that we add in our form and Form1.cs file contains all the events, custom code of our application. When these files gets compiled, they gets combined into one class.

Like we declare classes, Structs, Interfaces partial, we can declare partial methods as well. following are the conditions while declaring partial methods.
  • We can declare partial methods in partial type (Class,Struct) only.
  • partial method signature is defined in one part of partial type and implementation in other part of partial type.
  • Return type of partial method should be void.
  • We can't use access modifier on partial methods. They are private by default.
If we only declared partial method and not provided any impementation for that, then compiler will ignore the signature of that method.

See below sample code where class partialClass splits in two parts with partial keyword and also defined partial method ShowMessage in one part and implemented in second part.

+
using System;
 
namespace partial_class_and_methods
{
    //partial class part1
    partial class partialClass
    {
        partial void ShowMessage(string message);
    }
 
    //partial class part2
    partial class partialClass
    {
        partial void ShowMessage(string message)
        {
            Console.WriteLine("Partial method declaration with message" + message );
        }
    }
}


1 comment :

Anonymous said...

Good explaination...!!!