Do I need to call base.METHOD after overriding it, and if so - when is it the right time ?
Well, I'm glad you've asked; I had some chat with my co-worker about the subject when he did some overriding to the Form (WinForm) methods and he wasn't sure about when is it smart to call the base method and if so, should he call base.METHOD before implementing his code, or maybe after. To clarify, quick example:
public class MyForm : Form{ protected override void OnLoad(EventArgs e) { //OK, what here ???!!
// Custom code here ? //base.OnLoad(e); // should I ? // Or maybe - Custom code here... ? }}
After thinking for a few seconds, I came up with this explanation - sort of my "best practice" to the issue:
When do I call base.METHOD:
Do I call base.METHOD after my custom code, or maybe before:
This is a tricky one and there is not straight answer - my way of thinking and tackling this question is simply by Explore, Run & Learn "process" - meaning, try to Explore about the base method original purpose and try to figure out the logic; This will give you some logical direction whether you need to call the base method or not. For example - if you override the Render method, you can tell (by MSDN or by Reflector) that its rendering the entire object graph so you probably should call it (eventually). Now that you have some feeling about whether you need to write your code before or after the base.METHOD call, Run it and exam the results:
According to the results and the answers about the given questions, you should now have a clear vision about your decision. Make the required adjustments, place some important remarks(to describe your thinking at the moment) and feel good about your code, you did your best to get a good result. And most important - Learn from the process so it will be more natural on the next time you'll have to face this decision.
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2008, Oren Ellenbogen
<= Contact me via E-mail
newtelligence dasBlog 2.2.8279.16125