I have a tree of classes that describe interactive items, which in turn can be applied one onto another. When there's an attempt to do so, the base class checks on the type of the action target and chooses an appropriate handler method, which is overridden in descendants according to their purpose.
public abstract class BasicItem
{
public void Interact(BasicItem pair)
{
if(pair is Tool tool)
HandleInteractionWithTool(tool);
else if (pair is Container container)
HandleInteractionWithContainer(container);
else if(pair is Book book)
HandleInteractionWithBook(book);
}
protected virtual void HandleInteractionWithTool(Tool tool) { }
protected virtual void HandleInteractionWithContainer(Container container) {}
protected virtual void HandleInteractionWithBook(Book book) {}
}
public class Tool: BasicItem
{
protected override void HandleInteractionWithContainer(Container container)
{
//...
}
}
I suppose this is what can described as runtime type resolution.
I'm not a performance hypochondriac, and casting with is is not an issue.
What is an issue is that I already have about 15 classes among those "HandleInteractionWith..." methods, and the list is going to grow. It feels wrong, it looks wrong, and I'm ashamed of this "architecture".
Is there a better approach? Something tells me there's a pattern for this, and it involved generic methods.
The context is a Unity project, but I don't think it's very important.
Cheers.
I want to ask this question because of some safety mechanism for my code.
This may seem like useless, but it already made me lose much time debugging.
public class AnimalClass
{
virtual void Mod{}
virtual void UpdateSomeValues{}
}
public class CatClass : AnimalClass
{
override void Mod{}
override void UpdateSomeValues{}
}
Is there a way in C# to automatically fire up Cat's UpdateSomeValues function whenever Cat's Mod function is called (without having to call it manually from Cat's Mod function)?
And if possible, make it the same for all derived classes?
No. You could solve that issue by introducing another, protected method that derived classes can override, and make the public one call into it once all the necessary processing is done:
public class AnimalClass
{
public void Mod()
{
// do stuff
ModImpl();
}
protected virtual ModImpl() {}
}
With that derived classes would implement ModImpl() if they want to do some extra processing, and you're sure that // do stuff still happens when Mod is called.
I'm sorry if these types of questions aren't allowed.
I have a simple base for something similar to plugins.
Here's my example
class Plugin{
private bool _Enabled;
public bool Enabled{
get{
return _Enabled;
}
set{
_Enabled = value;
if(value)
MyExecutionHandler += Run;
}
}
public virtual void Run(object source, System.EventArgs args)
{
if(!Enabled)
return;
}
}
Now currently I'm doing something like this:
class CustomPlugin : Plugin{
public override void Run(object source, System.EventArgs args)
{
base.Run(source, args);
}
}
First of all is the logic behind this correct?
Secondly can I force them to implement the Run function from the partial class or do I need to create an interface for that?
You can define an abstract class with "default" behavior by declaring a method as virtual and overriding it in derived classes.
A derived class is not forced to override a virtual method in an abstract base class. If the method is not overridden, the behavior defined in the abstract class is used. Overriding the method can be used to replace the behavior entirely, or implement additional functionality (on top of calling base.MethodName()).
Unless I've misunderstood your question, this pattern should work for your scenario.
dotnetfiddle link: https://dotnetfiddle.net/7JQQ6I
Abstract base class:
public abstract class Plugin
{
public virtual string Output()
{
return "Default";
}
}
A derived class that uses the default implementation, and one that overrides it:
public class BoringPlugin : Plugin
{
public override string Output()
{
return base.Output();
}
}
public class ExcitingPlugin : Plugin
{
public override string Output()
{
return "No boring defaults here!";
}
}
Test result:
public static void Main()
{
var boring = new BoringPlugin();
Console.WriteLine(boring.Output());
var exciting = new ExcitingPlugin();
Console.WriteLine(exciting.Output());
}
Default
No boring defaults here!
This is not the correct way to use the partial keyword. The partial keyword merely allows you to spread the definition of a class into multiple source files. It isn't something you use to describe the architecture of your program. You would use it to split the definition into multiple files, something like this:
Plugin1.cs
partial class Plugin{
private bool _Enabled;
public bool Enabled{
get{
return _Enabled;
}
set{
_Enabled = value;
if(value)
MyExecutionHandler += Run;
}
}
}
Plugin2.cs
partial class Plugin {
public virtual void Run(object source, System.EventArgs args)
{
if(!Enabled)
return;
}
}
But this isn't helpful to you, and you should forget about the partial keyword (for now). You seem to be struggling with concepts related to object-oriented programming. The partial keyword has nothing to do with that, so don't worry about it.
If you want classes which inherit from Plugin to be 'forced' to implement the Run method, you should use an abstract method. HOWEVER, as you will read in that link, if you use an abstract method, you will not be able to define the 'default' behavior which you are currently defining in the body of the run method.
If you want classes which inherit from Plugin to be forced to define ADDITIONAL behavior, you can't really do that easily just using concepts like abstract classes / methods / interfaces. You will find it easier to compromise, and allow classes which inherit from plugin to 'just' have the default behavior of the Run method as described in your Plugin base class.
You will probably find this compromise acceptable. I think you will find that forcing classes which inherit from Plugin to do additional things in the Run method doesn't buy you anything. The behavior in the base Run method should still be considered a 'correct', if minimal / useless 'Run' of any type of derived Plugin.
I can't speak to the logic of your program, it isn't clear what you intend for these Plugins to do, but hopefully this will help you figure out exactly what you want to do, and how to do it.
I came across a posting where it is said that MustBeCalled() method will get called if we have the Abstract class do the calling in this manner.
public abstract class AbstractClass
{
public void PerformThisFunction()
{
MustBeCalled();
AbstractMethod();
}
public void MustBeCalled()
{
//this must be called when AbstractMethod is invoked
}
//could also be public if desired
protected abstract void AbstractMethod();
}
public class ImplementClass : AbstractClass
{
protected override void AbstractMethod()
{
//when called, base.MustBeCalled() must be called.
//how can i enforce this?
}
}
But how does MustBeCalled() method get called?
In what order things are called here?
If you call PerformFunction() first, then everything will execute in the intended order, where that order is specified in the order of the lines of code in PerformFunction(). If you call AbstractMethod() directly, there's no guarantee that MustBeCalled() will ever be called. However, I notice that you have AbstractMethod() marked as protected, which means that outside consumers of your class will not be able to call it directly. They'll have to use PerformFunction() -- this is good, as there is now only one public way to invoke your internal methods, and that way guarantees the order that you need.
In truth, there is a level at which you can only guarantee that things happen by choosing to write code to make them happen. You can't, for example, guarantee that code is going to implement a game of Tetris except by actually writing that code and choosing to implement it in such a way that it produces Tetris behavior. The type system and the public/protected/private modifiers can help some by preventing some misuse (as your internals are not accessible and thus cannot be invoked by consumers of your module), but they can only go so far. This is such a case.
You cannot enforce how an implementation to call a method when invoked. The implementation could do its own thing entirely, or do nothing.
public class ImplementClass : AbstractClass
{
protected override void AbstractMethod()
{
// this is a perfectly valid implementation
}
}
A better implementation could be.
public abstract class AbstractClass
{
public void PerformThisFunction()
{
MustBeCalled();
AbstractMethod();
}
private void MustBeCalled()
{
}
protected virtual void AbstractMethod()
{
MustBeCalled();
}
}
This way refactoring tools will at least create the desired boilerplate code:
public class ImplementClass : AbstractClass
{
protected override void AbstractMethod()
{
base.AbstractMethod();
}
}
However, the person overriding AbstractMethod still needs to call base.AbstractMethod, this is not enforced by the compiler at all.
Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..
--edit--
I am mainly curious about overriding methods.
There isn't and shouldn't be anything to do that.
The closest thing I can think of off hand if something like having this in the base class:
public virtual void BeforeFoo(){}
public void Foo()
{
this.BeforeFoo();
//do some stuff
this.AfterFoo();
}
public virtual void AfterFoo(){}
And allow the inheriting class override BeforeFoo and/or AfterFoo
Not in Java. It might be possible in C#, but someone else will have to speak to that.
If I understand correctly you want this:
class A {
public void foo() {
// Do superclass stuff
}
}
class B extends A {
public void foo() {
super.foo();
// Do subclass stuff
}
}
What you can do in Java to enforce usage of the superclass foo is something like:
class A {
public final void foo() {
// Do stuff
...
// Then delegate to subclass
fooImpl();
}
protected abstract void fooImpl();
}
class B extends A {
protected void fooImpl() {
// Do subclass stuff
}
}
It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.
Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.
EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.
The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.
This might be useful for scenarios where the method is invoked by some internal API.
i.e. where Foo() is not designed to be invoked directly:
public abstract class ExampleBase {
private bool _baseInvoked;
internal protected virtual void Foo() {
_baseInvoked = true;
// IMPORTANT: This must always be executed!
}
internal void InvokeFoo() {
Foo();
if (!_baseInvoked)
throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
}
}
Works:
public class ExampleA : ExampleBase {
protected override void Foo() {
base.Foo();
}
}
Yells:
public class ExampleB : ExampleBase {
protected override void Foo() {
}
}
I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...
public abstract class Animal
{
protected abstract void Hello();
public void SayHello()
{
//Do some mandatory thing
Console.WriteLine("something mandatory");
Hello();
Console.WriteLine();
}
}
public class Dog : Animal
{
protected override void Hello()
{
Console.WriteLine("woof");
}
}
public class Cat : Animal
{
protected override void Hello()
{
Console.WriteLine("meow");
}
}
Example usage:
static void Main(string[] args)
{
var animals = new List<Animal>()
{
new Cat(),
new Dog(),
new Dog(),
new Dog()
};
animals.ForEach(animal => animal.SayHello());
Console.ReadKey();
}
Which produces:
You may want to look at this (call super antipatern) http://en.wikipedia.org/wiki/Call_super
If I understand correctly you want to enforce that your base class behaviour is not overriden, but still be able to extend it, then I'd use the template method design pattern and in C# don't include the virtual keyword in the method definition.
No. It is not possible. If you have to have a function that does some pre or post action do something like this:
internal class Class1
{
internal virtual void SomeFunc()
{
// no guarantee this code will run
}
internal void MakeSureICanDoSomething()
{
// do pre stuff I have to do
ThisCodeMayNotRun();
// do post stuff I have to do
}
internal virtual void ThisCodeMayNotRun()
{
// this code may or may not run depending on
// the derived class
}
}
I didn't read ALL the replies here; however, I was considering the same question. After reviewing what I REALLY wanted to do, it seemed to me that if I want to FORCE the call to the base method that I should not have declared the base method virtual (override-able) in the first place.
Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.
Don't think there's any feasible solution built-in. I'm sure there's separate code analysis tools that can do that, though.
EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.
In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.
class Parent {
protected Parent(int id) {
}
}
class Child : Parent {
// Does not compile
public Child() {}
// Also does not compile
public Child(int id) { }
// Compiles
public Child() :base(42) {}
}
In java, the compiler can only enforce this in the case of Constructors.
A constructor must be called all the way up the inheritance chain .. ie if Dog extends Animal extends Thing, the constructor for Dog must call a constructor for Animal must call a constructor for Thing.
This is not the case for regular methods, where the programmer must explicitly call a super implementation if necessary.
The only way to enforce some base implementation code to be run is to split override-able code into a separate method call:
public class Super
{
public final void doIt()
{
// cannot be overridden
doItSub();
}
protected void doItSub()
{
// override this
}
}
public class Sub extends Super
{
protected void doItSub()
{
// override logic
}
}
I stumbled on to this post and didn't necessarily like any particular answer, so I figured I would provide my own ...
There is no way in C# to enforce that the base method is called. Therefore coding as such is considered an anti-pattern since a follow-up developer may not realize they must call the base method else the class will be in an incomplete or bad state.
However, I have found circumstances where this type of functionality is required and can be fulfilled accordingly. Usually the derived class needs a resource of the base class. In order to get the resource, which normally might be exposed via a property, it is instead exposed via a method. The derived class has no choice but to call the method to get the resource, therefore ensuring that the base class method is executed.
The next logical question one might ask is why not put it in the constructor instead? The reason is that it may be an order of operations issue. At the time the class is constructed, there may be some inputs still missing.
Does this get away from the question? Yes and no. Yes, it does force the derived class to call a particular base class method. No, it does not do this with the override keyword. Could this be helpful to an individual looking for an answer to this post, maybe.
I'm not preaching this as gospel, and if individuals see a downside to this approach, I would love to hear about it.
On the Android platform there is a Java annotation called 'CallSuper' that enforces the calling of the base method at compile time (although this check is quite basic). Probably the same type of mechanism can be easily implemented in Java in the same exact way. https://developer.android.com/reference/androidx/annotation/CallSuper