Why We’re Partial to Partial Methods
By James Sahaj, Project Manager for the Synergy .NET Compiler
A class that implements an interface must implement all members of that interface in order to compile and run successfully. But what if you wanted to give the implementer of a class a choice of whether or not to implement particular methods, and then have all calls associated with any unimplemented methods removed? This is the purpose of partial methods.
Partial methods, which were introduced in version 10.1.1a, allow the designer of a class to specify the methods that may be optionally implemented by the programmer who uses that class. Partial methods have two parts: a signature definition and an optional implementation.
In this scenario, the designer declares a partial class and then specifies two partial methods, giving only their signatures, but not giving them implementations:
namespace ns1 public partial class class1 static partial method meth1, void parm1, int endmethod static partial method meth1, void parm1, string endmethod public static method testit, void proc ns1.class1.meth1(8); ns1.class1.meth1("hey") end endclass endnamespace
The programmer using this class can then optionally define the implementation of the partial methods he wishes to implement:
namespace ns1 public partial class class1 static partial method meth1, void parm1, int proc Console.WriteLine("meth1(int)"); endmethod static partial method meth1, void parm1, string proc Console.WriteLine("meth1(string)"); endmethod endclass endnamespace main proc ns1.class1.testit() end
The output of the program is as follows:
So far, there isn’t much difference between a partial method and a regular defined method. However, suppose the implementer of the class only implemented the meth1(int) partial method. When compiling the program, the Synergy .NET compiler would detect that the meth1(string) partial method does not have an implementation and remove all the calls to meth1(string) from the executable at compile time! So, by not implementing that method the programmer can control which calls will be ignored.
Of course, to be able to remove method calls, partial methods must adhere to some basic restrictions:
- They must be in a partial class.
- They must return void.
- Their parameters cannot be marked with an OUT attribute.
- They must be private, so they cannot be called outside of the partial class.
- They cannot be virtual.
Using partial methods allows the designer of a class to give some calling flexibility to the programming consumers of that class by allowing them to determine which methods are implemented, and, in turn, which methods are called. Partial methods were added as part of the 10.1.1a patch. See METHOD-ENDMETHOD in the Synergy/DE documentation for more details on this wonderful new language feature.