Partial Methods In C#

We already have the concept of Partial Classes in C# but I never knew that we can also have Partial Methods. Yes, we can have Partial Methods in C#. This concept also uses the Partial keyword but there are some restrictions/guidelines with the use of the Partial Methods. These are given below.
  1. A Partial Method can only be created in other Partial Classes or Partial Structs.
  2. In order to create a Partial method, it must be declared first(like an abstract method), with a signature only and no definition. After it is declared, its body can be defined in the same component or different component of the Partial Class/Struct .
  3. A Partial Method is implicitly private. It cannot have any other access modifier.
  4. A Partial Method can only have void return type.
Let's see how we can create a Partial Method. We start by creating a Partial Class ClassA and add a Partial Method declaration.
  1. public partial class ClassA  
  2.    {  
  3.        partial void GetData();  
  4.    }  
Now, create the second component of the Partial Class ClassA and add the implementation of the Partial Method. 
  1. public partial class ClassA  
  2.   {  
  3.       partial void SetData()  
  4.       {  
  5.           // Perform functionality here  
  6.       }  
  7.   }  
In order to test the Partial Method, we add another method and call this private method inside this newly created method.
  1. class Program  
  2.    {  
  3.        static void Main(string[] args)  
  4.        {  
  5.            ClassA cls = new ClassA();  
  6.            cls.SetSalary();  
  7.        }  
  8.    }  
  9.    public partial class ClassA  
  10.    {  
  11.        partial void SetData();  
  12.    }  
  13.   
  14.    public partial class ClassA  
  15.    {  
  16.        public void SetSalary()  
  17.        {  
  18.            SetData();  
  19.            // Perform other functionality here  
  20.        }  
  21.        partial void SetData()  
  22.        {  
  23.            Console.Write("This is partial method.");  
  24.            Console.ReadKey();  
  25.        }  
  26.    }  
Run the code and see the result. I hope you enjoyed reading it. Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all