I want to call a partial method from outside of the declaring class. This is not allowed as partial methods are implicitly private. You can not set a delegate to point to a partial so I am proposing the following:
public partial class MyClass {
AnotherClass _anotherClass;
public MyClass () {
_anotherClass = new AnotherClass();
_anotherClass.Method = new Action(() => {
this.Method();
});
}
partial void Method();
//sometimes this method will be implemented
//partial void Method() {
//do something
//}
}
public class AnotherClass {
public Action Method { get; set;}
public void SomeOtherMethod(){
this.Method();
}
}
The classes are tightly coupled, they are in a parent child relationship. I want the parent to have a method that it can override to know about property changes on the child. I could attach event handlers to each of the children however the child already knows about its parent so having the child inform the parent directly seems like the way to go. Except when the parent does not care which is why I want to be able to implement a partial if I do care. This question is basically about ease of programming vs performance. I know I could attach event handlers only to the situation where I do care, but with the implementation as above I can generate all the partial methods and only implement the partials if I care.
My question relates to the times that the partial method Method()
is not implemented. When the Action method is called will the compiler optimise it away as its body is empty? If I get a heap of these Action calls being made could I suffer a performance penalty? Is there a better way to get the same functionality?
Per, MSDN (emphasis added):
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.
Thus, no real penalty as the calls are optimized away.