Partial Methods In C#

The partial keyword in a C# method creates a partial method. In this article, you will learn about partial methods in C# and how to use a partial method in your .NET application.

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.
C# Partial method
Here is a list of attributes of a partial method.
  1. A partial method can only be created in 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.    }  
  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.