Partial Methods (just found out)
I just found out about the partial method existence.
You can think about partial method as virtual method for partial scope.
In case you having your own code generator like Templates, VS designers or Custom tools,
i assume that you familiar with the following scenario:
You code generating partial class and you want to give class consumer the ability to intercept (hook) the class initialization.
Traditionally we may think about one of the followings:
- one option is to avoid writing your own constructor, but what if you need one?
- you may think of virtual method? but the consumer does not inherit the class (its partial).
- so maybe having private event? ye bat haw can the consumer register to the event without having access to the constructor?
This is the place that partial method help you, and it look like this:
Your generated code:
public partial class MyClass {
public MyClass () {
OnInit (); // will compile to IL only if implement
}
partial void OnInit (); // will compile to IL only if implement
}
The consumer code:
partial class MyClass {
partial void OnInit () {
// consumer logic goes here
}
}
The MSDN definition and limitation:
A partial method has its signature defined in one part of a partial type, and its implementation defined in another part of the type. Partial methods enable class designers to provide method hooks, similar to event handlers, that developers may decide to implement or not. If the developer does not supply an implementation, the compiler removes the signature at compile time. The following conditions apply to partial methods:
-
Signatures in both parts of the partial type must match.
-
The method must return void.
-
No access modifiers or attributes are allowed. Partial methods are implicitly private.