A partial method allows us to separate method definition and implementation. It does not mean that it would allow us multiple implementations. Only a partial class or struct may contain a partial method. One part of the partial class or struct has only declaration and another part of the same partial class or struct may have implementation for that. We can have both in the same part of the partial class or struct. A user may or may not implement the method. A partial method gets executed only when it has an implementation. If the user has not implemented them, the compiler does not include them in the final code.
Rules for Partial Methods:
- Partial methods are indicated by the partial modifier.
- Partial methods must be private.
- Partial methods must return void.
- Partial methods must only be declared within partial classes.
- Partial methods do not always have an implementation.
- Partial methods can be static and generic.
- Partial methods can have arguments including ref but not out.
- We cannot make a delegate to a partial method.
Example:
- namespace TestPartialMethods
- {
- class Program
- {
- static void Main(string[] args)
- {
- Student obj = new Student();
- Console.ReadLine();
- }
- }
- public partial class Student
- {
- public Student ()
- {
- Admission() ;
- }
-
-
- partial void Admission();
- }
- public partial class Student
- {
-
- partial void Admission()
- {
- Console.WriteLine("Inside implementation");
- }
- }
-
- }
Partial methods are useful to customize the code generated by any tool. The generated code may have some partial methods. Implementation of these methods is decided by the developers. If developer decide not to implement then compiler would removes them in the final code. It can also be helpful to distribute the development task among the team members.