Partial Methods

A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time. Partial methods enable the implementer of one part of a class to define a method and the implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. The calls to the method, including any results that would occur from evaluation of arguments in the calls, have no effect at run time. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile- time or run-time errors will result if the method is called but not implemented.


A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

partial void TestMethod(); // Definition in file1.cs
partial void TestMethod() { // Implementation in file2.cs
// method body
}
  • There are several rules to follow with partial class and there are several rules to follow with partial method as defined by Microsoft. Those rules are listed below:
  • Partial methods are indicated by the partial modifier and can be declared within partial classes only.
  • Partial methods must be private and must return void.
  • Partial methods do not always have an implementation and can also be declared as static.
  • Partial methods can have arguments including ref but not out.
  • You cannot make a delegate to a partial method.
  • Add 2 new code files Test1.cs and Test2.cs and write the following code:
    using System;
    namespace OOPSProject {
    	partial class PMethod {
    		partial void TestMethod();
    		public void Show() {
    			Console.WriteLine("Show Method.");
    		}
    	}
    }
    using System;
    namespace OOPSProject {
    	partial class PMethod {
    		partial void TestMethod() {
    			Console.WriteLine("Partial Method Implemented.");
    		}
    		public void s() {
    			Console.WriteLine("Display Method.");
    		}
    		static void Main() {
    			PMethod obj = new PMethod();
    			obj.Show();
    			obj.Display();
    			obj.TestMethod();
    			Console.ReadLine();
    		}
    	}
    }