Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make sure base method gets called in C#

Tags:

Can I somehow force a derived class to always call the overridden methods base?

public class BaseClass {     public virtual void Update()     {         if(condition)         {             throw new Exception("..."); // Prevent derived method to be called         }     } } 

And then in a derived class :

public override void Update() {     base.Update(); // Forced call      // Do any work } 

I've searched and found a suggestion to use a non-virtual Update() but also a protected virtual UpdateEx(). It just doesn't feel very neat, isn't there any better way?

I hope you get the question and I am sorry for any bad English.

like image 713
Matteus Hemström Avatar asked May 31 '10 17:05

Matteus Hemström


People also ask

Can you call the base call method without creating an instance?

"Can we call the base class's function without creating its object?" Well that question doesn't mean anything, but I would say no, you can't call upon base class functions prior to it's initialization which is why you generally have to call super before doing anything else.

How do I call a base call method in C#?

base (C# Reference)The base keyword is used to access members of the base class from within a derived class: Call a method on the base class that has been overridden by another method. Specify which base-class constructor should be called when creating instances of the derived class.

What does base mean in C?

The base keyword is used to access members in the base class that have been overridden (or hidden) by members in the subclass.

Can we call virtual method in C#?

C# virtual method is a method that can be redefined in derived classes. In C#, a virtual method has an implementation in a base class as well as derived the class. It is used when a method's basic functionality is the same but sometimes more functionality is needed in the derived class.


1 Answers

Use the template method pattern - don't override the base method which needs to do some work, override one specific bit, which can either be abstract or a no-op in the base class. (The decision about whether to make it a no-op or abstract is usually fairly obvious - does the base class make sense on its own, as a concrete class?)

It sounds like this is basically the pattern you've found with UpdateEx - although it's usually UpdateImpl or something similar in my experience. There's nothing wrong with this as a pattern, in my view - it avoids any idea of forcing all derived classes to write the same code to call the base method.

like image 199
Jon Skeet Avatar answered Sep 18 '22 13:09

Jon Skeet