C#: Override inherited method, but not for the whole class - c#

I'm just playing around a bit with inheritance and/or polymorphism in C#, and since my OOP skills are very, very basic I'm wondering if this is possible:
I have a class which inherits a method from a base class:
class BaseClass {
public void Init () {
// Do basic stuff.
}
}
class LoginTest : BaseClass {
public void StraightMethod () {
// Do stuff based on the actions in the inherited Init() method from BaseClass.
}
public void ExceptionMethod () {
// Do stuff where I don't want to do the actions in the inherited method.
// That is, skip or override the Init() method in the BaseClass class.
}
}
I know I can override the Init() method for the whole class, but is it possible to override it, or the code in it, for just the ExceptionMethod() method? These methods are run exclusively, so that for example one initialization of the LoginTest class will only run LoginClass.ExceptionMethod(), while another one might run LoginClass.StraightMethod().
And yes, I know that good design will eliminate the need for things like this. But first of all, I'm not doing software engineering here, so being pragmatic is often OK without ruining some design or other principles. Second, this is more a question of whether or not something can be done, rather than the wiseness of it.
Note that these classes and methods are UnitTest methods, so the Init() method is a [TestInitialize] method. Hence, it's called automatically when LoginTest inherits from the BaseClass.

No, you can't selectively override the Init method, but by making the Init method virtual, you can specify which version of the method you want to call with the base and this keywords:
class BaseClass
{
// This method must become virtual
public virtual void Init()
{
// Do basic stuff.
}
}
class LoginTest : BaseClass
{
public override void Init()
{
// Other stuff
}
public void StraightMethod()
{
// Do stuff based on the actions in the inherited Init() method from BaseClass.
base.Init();
}
public void ExceptionMethod()
{
// Do stuff where I don't want to do the actions in the inherited method.
// That is, skip or override the Init() method in the BaseClass class.
this.Init();
}
}

The method isn't virtual, so it's not possible to override it at all, ever.

You can't conditionally override the method, but you can call each one individually (if you provide the base functionality in the base class).
class BaseClass {
public virtual void Init () {
// Do basic stuff.
}
}
class LoginTest : Baseclass {
public override void Init() {
//do overridden stuff
}
public void StraightMehthod () {
this.Init(); // Call the overridden
}
public void ExceptionMethod () {
base.Init(); // Call the base specifically
}
}
As you have said though, this is probably not something you want to do as someone using this code will be very confused by the behavior.

You also have the option to do this.
class BaseClass
{
public void Init()
{
// Do basic stuff.
Console.WriteLine("BaseClass.Init");
}
}
class LoginTest : BaseClass
{
public void StraightMehthod()
{
// Do stuff based on the actions in the inherited Init() method from BaseClass.
base.Init();
}
public void ExceptionMethod()
{
// Do stuff where I don't want to do the actions in the inherited method.
this.Init();
// That is, skip or override the Init() method in the BaseClass class.
}
private new void Init()
{
Console.WriteLine("LoginTest.Init");
}
}

Related

Insert code from child class method in middle of base class method [duplicate]

I have a base class and a class inheriting base. The base class has several virtual functions that the inherited class may override. However, the virtual functions in the base class has code that MUST to run before the inherited class overrides get called. Is there some way that I can call the base classes virtual functions first then the inherited class overrides. Without making a call to base.function().
I know I can simply make two functions, one that gets called, the other virtual. But is there a way I can keep the same names as well? I know I may need to change some things around.
class myBase
{
public virtual myFunction()
{ /* must-run code, Called first */ }
}
class myInherited : myBase
{
public override myFunction()
{ /* don't use base.myFunction();,
called from base.myFunction(); */ }
}
Similar question here.
C# doesn't have support for automatically enforcing this, but
you can enforce it by using the template method pattern. For example, imagine you had this code:
abstract class Animal
{
public virtual void Speak()
{
Console.WriteLine("I'm an animal.");
}
}
class Dog : Animal
{
public override void Speak()
{
base.Speak();
Console.WriteLine("I'm a dog.");
}
}
The trouble here is that any class inheriting from Animal needs to call base.Speak(); to ensure the base behavior is executed. You can automatically enforce this by taking the following (slightly different) approach:
abstract class Animal
{
public void Speak()
{
Console.WriteLine("I'm an animal.");
DoSpeak();
}
protected abstract void DoSpeak();
}
class Dog : Animal
{
protected override void DoSpeak()
{
Console.WriteLine("I'm a dog.");
}
}
In this case, clients still only see the polymorphic Speak method, but the Animal.Speak behavior is guaranteed to execute. The problem is that if you have further inheritance (e.g. class Dachshund : Dog), you have to create yet another abstract method if you want Dog.Speak to be guaranteed to execute.
A common solution that can be found in the .NET Framework is to split a method in a public method XXX and a protected, virtual method OnXXX that is called by the public method. For your example, it would look like this:
class MyBase
{
public void MyMethod()
{
// do something
OnMyMethod();
// do something
}
protected virtual void OnMyMethod()
{
}
}
and
class MyInherited : MyBase
{
protected override void OnMyMethod()
{
// do something
}
}
public abstract class BaseTemp
{
public void printBase() {
Console.WriteLine("base");
print();
}
public abstract void print();
}
public class TempA: BaseTemp
{
public override void print()
{
Console.WriteLine("TempA");
}
}
public class TempB: BaseTemp
{
public override void print()
{
Console.WriteLine("TempB");
}
}
There is no way to do what you're seeking other than the 2 ways you already named.
Either you make 2 functions in the base class, one that gets called and the other virtual.
Or you call base.functionName in the sub-class.
Not exactly. But I've done something similar using abstract methods.
Abstract methods must be overriden by derived classes. Abstract procs are virtual so you can be sure that when the base class calls them the derived class's version is called. Then have your base class's "Must Run Code" call the abstract proc after running. voila, your base class's code always runs first (make sure the base class proc is no longer virtual) followed by your derived class's code.
class myBase
{
public /* virtual */ myFunction() // remove virtual as we always want base class's function called here
{ /* must-run code, Called first */
// call derived object's code
myDerivedMustcallFunction();
}
public abstract myDerivedMustCallFunction() { /* abstract functions are blank */ }
}
class myInherited : myBase
{
public override myDerivedMustCallFunction()
{ /* code to be run in derived class here */ }
}
What do you think of this?
class myBase
{
public void myFunctionWrapper()
{
// do stuff that must happen first
// then call overridden function
this.myFunction();
}
public virtual void myFunction(){
// default implementation that can be overriden
}
}
class myInherited : myBase
{
public override void myFunction()
{
}
}

How do I call the top ancestor method [duplicate]

class GrandParent
{
public virtual void Foo() { ... }
}
class Parent : GrandParent
{
public override void Foo()
{
base.Foo();
//Do additional work
}
}
class Child : Parent
{
public override void Foo()
{
//How to skip Parent.Foo and just get to the GrandParent.Foo base?
//Do additional work
}
}
As the code above shows, how can I have the Child.Foo() make a call into GrandParent.Foo() instead of going into Parent.Foo()? base.Foo() takes me to the Parent class first.
Your design is wrong if you need this.
Instead, put the per-class logic in DoFoo and don't call base.DoFoo when you don't need to.
class GrandParent
{
public void Foo()
{
// base logic that should always run here:
// ...
this.DoFoo(); // call derived logic
}
protected virtual void DoFoo() { }
}
class Parent : GrandParent
{
protected override void DoFoo()
{
// Do additional work (no need to call base.DoFoo)
}
}
class Child : Parent
{
protected override void DoFoo()
{
// Do additional work (no need to call base.DoFoo)
}
}
I think there is something wrong with your design here. Essentially, you want to "break" the rules of polymorphism. You are saying Child should derive from Parent but want to conveniently skip the implementation in it's parent.
Re-think your design.
No. It wouldn't be reliable anyway. You, as the implementer of your class, get to choose your immediate base class. But who is to say that a later release of Parent might not inherit from ParentBase, that in turn inherits from GrandParent? So long as Parent is still implementing the correct contract, this should not cause any issues for those classes inheriting from Parent.
No, this isn't possible. Imagine how crazy things would be if this was possible.
If you want something specific skipped in the Child case, consider reworking your design to better represent what you need (e.g. maybe you need to override something else in the Child class, too). Or, you could provide another Foo() in the Parent class that doesn't do anything except call its base.Foo().
If you have control of the code, the simplest way is to create a protected method in Parent class that only call base.Foo() and your child class Foo implementation call that method explicitly
We had exactly this scenario on a large project where the derived methods were called from various locations. Due to change management and QA scripts not to be broken, among other constraints, "drastic" refactoring and class re-structuring are not always possible on a large mature project. Also we did not want to override the method and exclude all base functionality. Most solutions seen elsewhere, looked a bit clumsy, but the solution from Josh Jordan on How to call base.base was quite useful.
However we followed the approach below (which I see now is very similar to what Dan Abramov propose).
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Hello from Base");
}
}
public class Derived : Base
{
public override void Foo()
{
base.Foo();
Console.WriteLine("Text 1");
WriteText2Func();
Console.WriteLine("Text 3");
}
protected virtual void WriteText2Func()
{
Console.WriteLine("Text 2");
}
}
public class Special : Derived
{
public override void WriteText2Func()
{
//WriteText2Func will write nothing when method Foo is called from class Special.
//Also it can be modified to do something else.
}
}
All these strong opinions...
Sometimes it just makes sense to use 99% of something...
public class Base
{
public virtual void Foo()
{
// Do something
}
}
public class DerivedLevel1 : Base
{
public override void Foo()
{
DerivedLevel1Foo();
}
protected void DerivedLevel1Foo()
{
// Do something
base.Foo();
}
}
public class DerivedLevel2 : DerivedLevel1
{
public override void Foo()
{
DerivedLevel2Foo();
}
protected void DerviedLevel2Foo()
{
// Do something
base.Foo();
}
}
public class Special : Derived
{
public override void Foo()
{
// Don't do DerivedLevel2Foo()
base.DerivedLevel1Foo();
}
}

How to call top class constructor?

I hope I can explain this problem right, it's a bit confusing for me.
I have been working on a game library similar to flixel but, using C#'s XNA framework instead of Flash. Right now the current class layout is something like this.
ClxBasic -> ClxObject -> ClxSprite
Each class has a constructor and calls the constructor for the class below it. I use this code to do this.
namespace Test
{
public class ClxBasic
{
public ClxBasic()
{
Constructor();
}
public void Constructor()
{
DoSomething();
}
}
public class ClxObject : ClxBasic
{
public ClxObject() : base()
{
Constructor();
}
public void Constructor()
{
DoSomething();
}
}
public class ClxSprite : ClxObject
{
public ClxSprite() : base()
{
Constructor();
}
public void Constructor()
{
DoSomething();
}
}
}
So basically when I create a new ClxSprite it calls the ClxSprite constructor, then all the ones below it (ClxObject and ClxBasic).
I'm sure there is an easier way to do this and I am all ears.
However, my bigger issue is actually how to properly derive and override methods from the other classes.
The issue is that when creating a class that extends from ClxSprite, for example, when calling a method that was overridden from the most basic class (ClxBasic), it will only call the bottom method and not the top.
The reason I need to do this is because I have a global class which keeps control of all the objects derived from ClxBasic by adding themselves to a list in the ClxBasic constructor.
Here's some example code.
namespace Test
{
public static class ClxG()
{
public static List<ClxBasic> GlobalObjects; //All objects will be added here by the ClxBasic constructor
ClxSprite test = new ClxSprite();
GlobalObjects.Add(test);
public static Update()
{
foreach(ClxBasic basic in GlobalObjects)
basic.Update(); //Calling this calls ClxBasic.Update() when it should call ClxSprite.Update()
}
}
}
When calling basic.Update() it goes to the bottom Update, the one located in ClxBasic, despite the object being a ClxObject or ClxSprite or other derived class.
I have a limited fix as well, by changing the ClxBasic to ClxSprite in the foreach loop, you can call that classes constructor method properly. However, when making custom classes based off of the library who override a method, the lower Update is called.
However, the limit is that you can't add classes I didn't specifically plan for. For example, if I were to derive a class Player from ClxSprite and, override the Update() method, it would get added to the GlobalObjects list but, never have it's update called, the highest it will go is ClxSprite's.
The way I want it to work is, in Game1.cs I want to just be able to put FlxG.Update() in the Game.Update() loop and just be able to create the object and have my framework handle the rest.
I hope I've made a bit of sense, the whole thing feels like some sort of inheritance inception and kind of makes my brain hurt.
To also call a base class method as part of a child class implementation, you'd do this:
class Base {
public virtual void Method() {
// ...
}
}
class Derived : Base {
public override void Method() {
base.Method();
// ....
}
}
class Derived2 : Derived {
public override void Method() {
base.Method();
// ....
}
}
But the child method is not required to call the base one.
Constructors, on the other hand, are always required to (ultimately) call a base constructor.
Now, if you want a base class method to always be called as part of some processing, you can employ the template method pattern. Basically your base class has a non-virtual method that drives an algorithm that calls virtual (or abstract) methods; which the child classes can override to create their own versions.
You are properly using base() to call the constructors of your base classes. As for how you are defining your constructors, why is Constructor() a separate method, rather than the body of the different constructors? If you are only planning on calling Constructor() when you create a new insance of one of your classes, I would recommend moving Constructor() back into your actual constructors, like so:
namespace Test
{
public class ClxBasic
{
public ClxBasic()
{
// Do Something
}
}
public class ClxObject : ClxBasic
{
public ClxObject() : base()
{
// Do Something
}
}
public class ClxSprite : ClxObject
{
public ClxSprite() : base()
{
// Do Something
}
}
}
As for being able to call the appropriate Update() function, depending on the actual class of your object, you would accomplish this using the virtual and override keywords. You would use them like so:
namespace Test
{
public class ClxBasic
{
// Define the base function that can be overridden
// in subclasses.
public virtual void Update()
{
// Do Some Updates
}
}
public class ClxObject : ClxBasic
{
// We're overridiung the base function, so we
// must mark this function as an override.
public override void Update()
{
// Do Some Updates
}
}
public class ClxSprite : ClxObject
{
// We're overridiung the base function, so we
// must mark this function as an override.
public override void Update()
{
// Do Some Updates
}
}
}
When you call Update() on an object that is an instance of a class derived from ClxBasic, the top-level Update() function in that objects inheritance-chain will be called. For instance:
ClxBasic clxBasic = new ClxBasic(); // Calls ClxBasic.Update()
ClxBasic clxObject = new ClxObject(); // Calls ClxObject.Update()
ClxBasic clxSprite = new ClxSprite(); // Calls ClxSprite.Update()
In addition, if you want your Update() functions to call the Update() function of their parent, you can use the base keyword.
For example:
public class ClxSprite : ClxObject
{
// We're overridiung the base function, so we
// must mark this function as an override.
public override void Update()
{
base.Update(); // Will call ClxObject's Update() function
// Do Some Updates
}
}
Based on your description, your goal seems to be to achieve polymorphic behavior among different game classes. A better solution is to define an interface that different game classes must implement. Then you can put all of your game objects in one generic container, such as an array list, and then have the master game loop iterate through the object list and invoke each object's update method the method during each overall update. I would design the classes like this:
interface IUpdatable {
void doUpdate();
}
class GameClassA : IUpdatable {
void doUpdate() { // }
}
class GameClassB : IUpdatable {
void doUpdate() { // }
}
etc.
Your goal is to achieve polymorphic behavior among objects of different classes but not necessarily to share data and common functionality. While you can achieve polymorphism through inheritance as well, it is better achieved in this case through simple interfaces and composition.

C# How to execute code after object construction (postconstruction)

As you can see in the code below, the DoStuff() method is getting called before the Init() one during the construction of a Child object.
I'm in a situation where I have numerous child classes. Therefore, repeating a call to the DoStuff() method directly after Init() in the constructor of each child wouldn't be an elegant solution.
Is there any way I could create some kind of post constructor in the parent class that would be executed after the child's constructor? This way, I could call to the DoStuff() method there.
If you have any other design idea which could solve my problem, I'd like to hear it too!
abstract class Parent
{
public Parent()
{
DoStuff();
}
protected abstract void DoStuff();
}
class Child : Parent
{
public Child()
// DoStuff is called here before Init
// because of the preconstruction
{
Init();
}
private void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
If you have a complex logic for constructing your objects then consider FactoryMethod pattern.
In your case I would implement it as a simple
public static Parent Construct(someParam)
method that takes some parameter and based on it decides which child class to instantiate.
You can remove your DoStuff() method call from the constructor and call it inside Construct() on the new instance.
Also, you should avoid virtual/abstract method calls in the constructors. See this question for more details: Virtual member call in a constructor
Let me introduce a general solution using some C# features. Note that this solution does not require you to use a factory pattern or invoke anything after constructing the object, and it works on any class with just implementing an interface with a single method.
First we declare an interface that our classes will have to implement:
public interface IInitialize {
void OnInitialize();
}
Next we add a static extension class for this interface, and add the Initialize method:
public static class InitializeExtensions
{
public static void Initialize<T>(this T obj) where T: IInitialize
{
if (obj.GetType() == typeof(T))
obj.OnInitialize();
}
}
Now, if we need a class and all of its descendants to call an initializer right after the object is fully constructed, all we need to do is implement IInitialize and append a line in the constructor:
public class Parent : IInitialize
{
public virtual void OnInitialize()
{
Console.WriteLine("Parent");
}
public Parent()
{
this.Initialize();
}
}
public class Child : Parent
{
public Child()
{
this.Initialize();
}
public override void OnInitialize()
{
Console.WriteLine("Child");
}
}
public class GrandChild : Child
{
public GrandChild()
{
this.Initialize();
}
public override void OnInitialize()
{
Console.WriteLine("GrandChild");
}
}
The trick is that when a derived class calls the extension method Initialize, that will suppress any calls not made from the actual class.
How about this:
abstract class Parent
{
public Parent()
{
Init();
DoStuff();
}
protected abstract void DoStuff();
protected abstract void Init();
}
class Child : Parent
{
public Child()
{
}
protected override void Init()
{
// needs to be called before doing stuff
}
protected override void DoStuff()
{
// stuff
}
}
As others have mentioned, you should use a Factory Pattern.
public class Parent
{
public Parent()
{
}
public virtual void PostConstructor()
{
}
}
public class Child : Parent
{
public override void PostConstructor()
{
base.PostConstructor();
// Your code here
}
}
public void FactoryMethod<T>() where T : Parent
{
T newobject = new T();
newobject.PostConstructor();
}
I would strongly suggest use Factory like a pattern.
If it's possible:
1. Push all your childs and abstract class into separate assembly.
2. Declare ctors of childs like internal methods, so no one out of that assembly is can construct them just by calling ctor.
3. Implement the Factory class to construct for caller specified objects type, which obviuoly will forse calling of abstract DoStuff() method after actual creation of anobject, but before returning it to caller.
Good thing about this is that: It will give you also additional level of abstraction, so if in the future you will need some more functions call or any other type of logical complexity, what you will need, is just add them into your Factory class.
That is.
Regards
In WPF applications, you can postpone the invokation of DoStuff() with the help of Dispatcher:
abstract class Parent
{
public Parent()
{
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(this.DoStuff));
}
private void DoStuff()
{
// stuff, could also be abstract or virtual
}
}
However, it is not guaranteed that DoStuff() will be called immediately after the constructor.
Correction: As per this answer, you can't determine when the base class's constructor is invoked during construction of the subclass.
E.g. This doesn't work:
public Child()
// DoStuff is called here after Init
// because of the overridden default constructor
{
Init();
base();
}
So, yes, as others have noted, if sequence of events matters, then the base class needs to be able to accommodate that by declaring abstract methods in order, or (better yet) by having the child class's implementation of DoStuff represent the sequence of events:
protected override void DoStuff()
{
Init();
base.DoStuff();
}
DoStuff is abstract. Just call Init from the top of DoStuff.
class MyBase
{
public MyBase()
{
//... do something
// finally call post constructor
PostConstructor<MyBase>();
}
public void PostConstructor<T>( )
{
// check
if (GetType() != typeof(T))
return;
// info
System.Diagnostics.Debug.WriteLine("Post constructor : " + GetType());
}
}
class MyChild : MyBase
{
public MyChild()
{
// ... do something
// ... call post constructor
PostConstructor<MyChild>();
}
}
How about...
public MyClass()
{
Dispatcher.UIThread.Post(RunAfterConstructor);
}
I also tried with Task.Run but that didn't work reliably.
Rather than using an abstract method, which would require you to implement the method in all descendant classes, you might try:
public class Parent
{
public Parent()
{
PostConstructor();
}
protected virtual void PostConstructor()
{
}
}
public class Child : Parent
{
protected override void PostConstructor()
{
base.PostConstructor();
/// do whatever initialization here that you require
}
}
public class ChildWithoutOverride
{
/// not necessary to override PostConstructor
}

C#: Any way to skip over one of the base calls in polymorphism?

class GrandParent
{
public virtual void Foo() { ... }
}
class Parent : GrandParent
{
public override void Foo()
{
base.Foo();
//Do additional work
}
}
class Child : Parent
{
public override void Foo()
{
//How to skip Parent.Foo and just get to the GrandParent.Foo base?
//Do additional work
}
}
As the code above shows, how can I have the Child.Foo() make a call into GrandParent.Foo() instead of going into Parent.Foo()? base.Foo() takes me to the Parent class first.
Your design is wrong if you need this.
Instead, put the per-class logic in DoFoo and don't call base.DoFoo when you don't need to.
class GrandParent
{
public void Foo()
{
// base logic that should always run here:
// ...
this.DoFoo(); // call derived logic
}
protected virtual void DoFoo() { }
}
class Parent : GrandParent
{
protected override void DoFoo()
{
// Do additional work (no need to call base.DoFoo)
}
}
class Child : Parent
{
protected override void DoFoo()
{
// Do additional work (no need to call base.DoFoo)
}
}
I think there is something wrong with your design here. Essentially, you want to "break" the rules of polymorphism. You are saying Child should derive from Parent but want to conveniently skip the implementation in it's parent.
Re-think your design.
No. It wouldn't be reliable anyway. You, as the implementer of your class, get to choose your immediate base class. But who is to say that a later release of Parent might not inherit from ParentBase, that in turn inherits from GrandParent? So long as Parent is still implementing the correct contract, this should not cause any issues for those classes inheriting from Parent.
No, this isn't possible. Imagine how crazy things would be if this was possible.
If you want something specific skipped in the Child case, consider reworking your design to better represent what you need (e.g. maybe you need to override something else in the Child class, too). Or, you could provide another Foo() in the Parent class that doesn't do anything except call its base.Foo().
If you have control of the code, the simplest way is to create a protected method in Parent class that only call base.Foo() and your child class Foo implementation call that method explicitly
We had exactly this scenario on a large project where the derived methods were called from various locations. Due to change management and QA scripts not to be broken, among other constraints, "drastic" refactoring and class re-structuring are not always possible on a large mature project. Also we did not want to override the method and exclude all base functionality. Most solutions seen elsewhere, looked a bit clumsy, but the solution from Josh Jordan on How to call base.base was quite useful.
However we followed the approach below (which I see now is very similar to what Dan Abramov propose).
public class Base
{
public virtual void Foo()
{
Console.WriteLine("Hello from Base");
}
}
public class Derived : Base
{
public override void Foo()
{
base.Foo();
Console.WriteLine("Text 1");
WriteText2Func();
Console.WriteLine("Text 3");
}
protected virtual void WriteText2Func()
{
Console.WriteLine("Text 2");
}
}
public class Special : Derived
{
public override void WriteText2Func()
{
//WriteText2Func will write nothing when method Foo is called from class Special.
//Also it can be modified to do something else.
}
}
All these strong opinions...
Sometimes it just makes sense to use 99% of something...
public class Base
{
public virtual void Foo()
{
// Do something
}
}
public class DerivedLevel1 : Base
{
public override void Foo()
{
DerivedLevel1Foo();
}
protected void DerivedLevel1Foo()
{
// Do something
base.Foo();
}
}
public class DerivedLevel2 : DerivedLevel1
{
public override void Foo()
{
DerivedLevel2Foo();
}
protected void DerviedLevel2Foo()
{
// Do something
base.Foo();
}
}
public class Special : Derived
{
public override void Foo()
{
// Don't do DerivedLevel2Foo()
base.DerivedLevel1Foo();
}
}

Categories