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.
- A Partial Method can only be created in other Partial Classes or Partial Structs.
- 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 .
- A Partial Method is implicitly private. It cannot have any other access modifier.
- 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.
- public partial class ClassA
- {
- partial void GetData();
- }
Now, create the second component of the Partial Class ClassA and add the implementation of the Partial Method.
- public partial class ClassA
- {
- partial void SetData()
- {
-
- }
- }
In order to test the Partial Method, we add another method and call this private method inside this newly created method.
- class Program
- {
- static void Main(string[] args)
- {
- ClassA cls = new ClassA();
- cls.SetSalary();
- }
- }
- public partial class ClassA
- {
- partial void SetData();
- }
-
- public partial class ClassA
- {
- public void SetSalary()
- {
- SetData();
-
- }
- partial void SetData()
- {
- Console.Write("This is partial method.");
- Console.ReadKey();
- }
- }
Run the code and see the result. I hope you enjoyed reading it. Happy coding.