Posted By: fabian | Aug 5th @ 8:55 AM
page 1 of 1
Comments: 5 | Views: 503

Small question. I you override a method does your custom logic go before or after the base call?

Looking throug samples and coworker code (and my own code Wink ) there seems to be no consensus. What is the correct way? Is there a correct way or does it depend on the task your are preforming?

 

protected override void OnPreRender(EventArgs e)

 { 

               DoStuffGoesHere() 

               base.OnPreRender(e); 

               OrDoesStuffGoesHere()

 }

Sven Groot
Sven Groot
My name has 9 letters. Coincidence? I think not...

It depends on what the base class function does and what you want to do. There is no single correct answer.

Usually when dealing with the built-in controls, I place the base class function first and then do my thing.

 

But as Sven said, there's no correct answer.

Dr Herbie
Dr Herbie
Horses for courses

Yes, you have to know how the base-class operates in order to override in the derived class -- this is why inheritance is a form of coupling (one class requires intimate knowledge of what the other does internally).

 

Recently, I have started to try and keep my inheritance coupling to a minimum: making protected properties backed by private variables and providing template pattern methods where a 'BeforeAction()' and an 'AfterAction()' virtual method are provided to override, rather than overriding the main method itself. This makes me design the derived and base classed to be less intimate.

This should mean that changes to the base or derived classes are less likely to impact the rest of the inheritance hierarchy.  So far I haven't kept any metrics so I don't know if the effort is worth it yet.  I guess time will tell ...

 

Herbie

 

There's three types of functionality that can be added to an override: functionality that needs to run first, functionality that needs to run last, and functionality that can run at any point.  If you're in the latter category, convention says to put your code after, so the majority of cases will come after. There's still those cases where it must come before, though, so there's no single right answer.

page 1 of 1
Comments: 5 | Views: 503
Microsoft Communities