overriding an interface method not marked as virtual - c#

I'm writing a log4net appender. They have an AppenderSkeleton class which implements IAppender:
public abstract class AppenderSkeleton : IBulkAppender,
IAppender, IOptionHandler
They way the AppenderSkeleton class works is they implement the DoAppend() method of IAppender and do a bunch of work for you, like calling the filter chain, and then call an abstract method called Append(). While this is reasonable, I would like to execute some of my code before the filters run. I could implement the IAppender interface myself but at first I figured I would just try to override DoAppend() in my derived class, do my stuff, and then call base.DoAppend(). It was at this point where I noticed the AppenderSkeleton didn't mark DoAppend() as virtual since I got a compiler error indicating I couldn't override the method since it wasn't marked virtual.
I then had my class derive from IAppender and explicitly implemented the IAppender.DoAppend() method. I was surprised that the code compiled without issues. Below is my DoAppend() method:
void IAppender.DoAppend(LoggingEvent evnt)
{
.
.
.
base.DoAppend(evnt);
}
I haven't tried running it yet but wondering if someone might now what the runtime will end up doing with this implementation?
Thanks,
Nick

#Rob's answer is right - which method (base or derived) is called would depend on how you invoked it. That would make it rather fragile code.
What I'd recommend is to use composition and not inheritance. Don't make your class inherit from AppenderSkeleton, make it contain an instance of AppenderSkeleton and use its methods where you choose to.
Visual Studio even has a quick "Implement interface through private variable" option if you declare a private variable that implements one of the interfaces your class also implements. It quickly generates a proxy pattern for your class, calling the corresponding methods on the private member.

If someone has not marked his method as virtual, then there is no way to override this. The only option is to implement your own IAppender.
Also, note that you do not override interface methods, you implement them.
However, you even do not need to override this method.
According to documentation, DoAppend
performs threshold checks and invokes filters before delegating actual logging to the subclasses specific Append method.
You don't need to override DoAppend method, since it describes the generic algorithm.
It is sort of Template method.
You need to override Append method which is abstract:
protected override void Append(LogginEvent loggingEvent)
{
// Your actions here
}

Related

Why is it required to have override keyword in front of abstract methods when we implement them in a child class?

When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword?
public abstract class Person
{
public Person()
{
}
protected virtual void Greet()
{
// code
}
protected abstract void SayHello();
}
public class Employee : Person
{
protected override void SayHello() // Why is override keyword necessary here?
{
throw new NotImplementedException();
}
protected override void Greet()
{
base.Greet();
}
}
Since the method is declared abstract in its parent class it doesn't have any implementation in the parent class, so why is the keyword override necessary here?
When we create a class that inherits from an abstract class and when we implement the inherited abstract class why do we have to use the override keyword?
"Why?" questions like this can be hard to answer because they are vague. I'm going to assume that your question is "what arguments could be made during language design to argue for the position that the override keyword is required?"
Let's start by taking a step back. In some languages, say, Java, methods are virtual by default and overridden automatically. The designers of C# were aware of this and considered it to be a minor flaw in Java. C# is not "Java with the stupid parts taken out" as some have said, but the designers of C# were keen to learn from the problematic design points of C, C++ and Java, and not replicate them in C#.
The C# designers considered overriding to be a possible source of bugs; after all, it is a way to change the behaviour of existing, tested code, and that is dangerous. Overriding is not something that should be done casually or by accident; it should be designed by someone thinking hard about it. That's why methods are not virtual by default, and why you are required to say that you are overriding a method.
That's the basic reasoning. We can now go into some more advanced reasoning.
StriplingWarrior's answer gives a good first cut at making a more advanced argument. The author of the derived class may be uninformed about the base class, may be intending to make a new method, and we should not allow the user to override by mistake.
Though this point is reasonable, there are a number of counterarguments, such as:
The author of a derived class has a responsibility to know everything about the base class! They are re-using that code, and they should do the due diligence to understand that code thoroughly before re-using it.
In your particular scenario the virtual method is abstract; it would be an error to not override it, and so it is unlikely that the author would be creating an implementation by accident.
Let's then make an even more advanced argument on this point. Under what circumstances can the author of a derived class be excused for not knowing what the base class does? Well, consider this scenario:
The base class author makes an abstract base class B.
The derived class author, on a different team, makes a derived class D with method M.
The base class author realizes that teams which extend base class B will always need to supply a method M, so the base class author adds abstract method M.
When class D is recompiled, what happens?
What we want to happen is the author of D is informed that something relevant has changed. The relevant thing that has changed is that M is now a requirement and that their implementation must be overloaded. D.M might need to change its behaviour once we know that it could be called from the base class. The correct thing to do is not to silently say "oh, D.M exists and extends B.M". The correct thing for the compiler to do is fail, and say "hey, author of D, check out this assumption of yours which is no longer valid and fix your code if necessary".
In your example, suppose the override was optional on SayHello because it is overriding an abstract method. There are two possibilities: (1) the author of the code intends to override an abstract method, or (2) the overriding method is overriding by accident because someone else changed the base class, and the code is now wrong in some subtle way. We cannot tell these possibilities apart if override is optional.
But if override is required then we can tell apart three scenarios. If there is a possible mistake in the code then override is missing. If it is intentionally overriding then override is present. And if it is intentionally not overriding then new is present. C#'s design enables us to make these subtle distinctions.
Remember compiler error reporting requires reading the mind of the developer; the compiler must deduce from wrong code what correct code the author likely had in mind, and give an error that points them in the correct direction. The more clues we can make the developer leave in the code about what they were thinking, the better a job the compiler can do in reporting errors and therefore the faster you can find and fix your bugs.
But more generally, C# was designed for a world in which code changes. A great many features of C# which appear "odd" are in fact there because they inform the developer when an assumption that used to be valid has become invalid because a base class changed. This class of bugs is called "brittle base class failures", and C# has a number of interesting mitigations for this failure class.
It's to specify whether you're trying to override another method in the parent class or create a new implementation unique to this level of the class hierarchy. It's conceivable that a programmer might not be aware of the existence of a method in a parent class with exactly the same signature as the one they create in their class, which could lead to some nasty surprises.
While it's true that an abstract method must be overridden in a non-abstract child class, the crafters of C# probably felt it's still better to be explicit about what you're trying to do.
Because abstract method is a virtual method with no implementation, per C# language specification, means that abstract method is implicitly a virtual method. And override is used to extend or modify the abstract or virtual implementation, as you can see here
To rephrase it a little bit - you use virtual methods to implement some kind of late binding, whereas abstract methods force the subclasses of the type to have the method explicitly overridden. That's the point, when method is virtual, it can be overridden, when it's an abstract - it must be overriden
To add to #StriplingWarrior's answer, I think it was also done to have a syntax that is consistent with overriding a virtual method in the base class.
public abstract class MyBase
{
public virtual void MyVirtualMethod() { }
public virtual void MyOtherVirtualMethod() { }
public abstract void MyAbtractMethod();
}
public class MyDerived : MyBase
{
// When overriding a virtual method in MyBase, we use the override keyword.
public override void MyVirtualMethod() { }
// If we want to hide the virtual method in MyBase, we use the new keyword.
public new void MyOtherVirtualMethod() { }
// Because MyAbtractMethod is abstract in MyBase, we have to override it:
// we can't hide it with new.
// For consistency with overriding a virtual method, we also use the override keyword.
public override void MyAbtractMethod() { }
}
So C# could have been designed so that you did not need the override keyword for overriding abstract methods, but I think the designers decided that would be confusing as it would not be consistent with overriding a virtual method.

How to automatic create override implementations of a base class?

I would like to know how could I create the implementation of an abstract method in all the specific classes that inherit from him.
I need it because I have an abstract class, I create one abstract method on it, but there is around 50 specific class to implement this method, and will be so boring implement one by one (even with the ctrl + . shortcut).
You can right-click on every class and select Implement Abstract Class which will create an empty metmber-body doing nothing but throw an NotImplementedException.
However I can´t see any reason why you should do that. If your method should have a default-implementation it should not be abstract in base-classd but virtual:
abstract class MyBaseClass {
virtual void DoSomething()
{
// do nothing
}
}
class Derived : MyBaseClass {
override void DoSomething()
{
Console.WriteLine();
}
}
You do not have to implement the method on all derived classes now. So as long as you´re testing (or for whatever weird reason you need this) you can stay on your default implementaion whereas when releasing the software you force every class to implement the member by chaning modifier from virtual to abstract and delete the method-body.
If I understand your problem correctly, you can follow the pattern of the adapters for Java event listeners.
They are an intermediate class sitting above the abstract class (interface in Java), providing a more or less meaningful (actually, empty) default implementation for all abstract functions. Your classes inherit (either just for now, or forever) from this adapter, overriding only some of the functions.
If all your classes inherit from this adapter as a permanent solution it is probably questionable why you had the abstract class to begin with. Defining an interface with no implementation makes sense only in order to avoid the restrictions concerning multiple inheritance in Java and C#. If the base class has some implementations anyway, you can as well provide a default for the remaining abstract methods, too. If that is undesired because in production code inheritors must be forced to implement their own methods, because there is no reasonable default, one could actually disable the implementing code with conditional translation (and, for example, make it dependent on a DEBUG or TEST flag during compilation).

C# - force overridden method to be called by parent, not by instance

I'm trying to find a proper way to restrict/force the usage of methods in order to ensure the correct internal handling.
Given the following abstract base class
public abstract class BaseClass
{
// needs to be overriden by concrete implementation
protected abstract void CreateInternal(object dataToCreate);
// only visible method
public void Create(object dataToCreate)
{
// check the data provided <-- this is important to be done each time
CheckData(dataToCreate);
// call implementation of concrete class
CreateInternal(dataToCreate);
}
private void CheckData(object dataToCheck)
{
if(dataToCheck == null) throw new Exception("Data is not valid");
}
}
and a simple implementation
public class ChildClass : BaseClass
{
protected override void CreateInternal(object dataToCreate)
{
// do create-stuff related to ChildClass
}
}
My question: Is there a way to restrict the access to CreateInternal? In ChildClass I could create a public method
public void DoStuff(object dataToDoStuff)
{
// access protected method is not forbidden
CreateInternal(dataToDoStuff);
}
This will call CreateInternal without doing the needed checks as if it would do if called via Create of the base-class.
Is there any way to force the usage of Create prior to CreateInternal? There is no need to have this at compile-time (but it would be nice), but at least at runtime.
I have something like checking who is calling in mind.
public class ChildClass : BaseClass
{
protected override void CreateInternal(object dataToCreate)
{
// if not called via base 'Create' -> throw exception
}
}
Is there some pattern I'm not aware of or is what I'm trying to achieve too weired and simply not possible?
There is no way of really enforcing this at compile or runtime. As you well say, a virtual protected method is reachable and overridable from any derived type so you'd always have to rely on the implementation of the overriden method making the necessary checks which kind of defeats the purpose.
IMHO your best bet is to enforce this through code reviews if you can control who's extending your class. If thats not the case then, seeing that your Create method is not virtual and is simply changing the state of BaseClass, why don't you call it in the constructor? Is this possible or is your example a simplified scenario and this isn't an option? Doing this would guarantee that Create is always called first.
UPDATE: Contrary to what I said before, there are "ways" you could enforce this at runtime.
Although not shown in your example, I'm guessing there will be some kind of internal state in BaseClass that any derived class must leverage via methods, properties, fields, etc. to be of any use (inheritance would be kind of pointless otherwise). You could always set a private flag createCalled in BaseClass and make all BaseClass methods, getters (yuck) and setters check the flag and bail out with an InvalidOperationException if its not set. This would esentially render useless any derived instance not correctly initialized. Ugly but doable.
Or even simpler, if you control all potential consumers of BaseClass and any derived type out there in the wild, then just make the flag public public bool Initialized { get; }and check when consuming the object and bail out if necessary.
"Weird" would not be the word of choice of mine, but still..
As far as I can see, what you are trying to achieve is to prevent the ChildClass owner, who implemented CreateInternal()'s method body, from executing those statements without invoking CheckData() first.
Even if this works, he can still copy and paste the statements into DoStuff() method body and can execute them there.
We do not force, we guide.
People will follow your guideline, and they will be happy to see that their class is working according to it.

Is there a C# equivalent of Java's #Override?

This has been asked before, but I could not get clarity from that answer, that's why I ask again...
Let's use two examples:
class implements interface
class extends an abstract class
My feeling is that with respect to the override keyword, both samples must behave identically. What is the desired goal of override? To prevent a method being dropped in a superclass or interface without being changed in all subclasses or implementing classes. So a compile time code consistency check.
In this C# code, compiling results in error: '....RepositoryContext.getXmlDoc()': no suitable method found to override:
interface IRepositoryContext
{
XmlDocument getXmlDoc();
}
class RepositoryContext : IRepositoryContext
{
private readonly XmlDocument gXmlDoc = new XmlDocument();
public override XmlDocument getXmlDoc() // does not compile
{
return gXmlDoc;
}
}
Whereas in this C# code, compilation works without any errors or warnings:
abstract class RepositoryContextBase
{
public abstract XmlDocument getXmlDoc();
}
class RepositoryContext : RepositoryContextBase
{
private readonly XmlDocument gXmlDoc = new XmlDocument();
public override XmlDocument getXmlDoc()
{
return gXmlDoc;
}
}
Is it a valid assumption that this should not work identically, or is there a way around this, or...?
The override modifier is defined thus:
The override modifier is required to extend or modify the abstract or virtual implementation of an inherited method, property, indexer, or event.
http://msdn.microsoft.com/en-us/library/ebca9ah3.aspx
The override keyword specifies that the method overrides an existing method implementation, which is why you don't need to specify it when you're implementing an interface directly - there is no such method to override; you're the first to implement it.
When you use the override keyword, you're essentially saying "for this class, call this method instead of the base method." This obviously doesn't apply when there is no such base method (e.g. when you are directly implementing an interface).
For virtual or abstract methods from classes, you need to insert the override keyword or it won't work at all.
For interfaces, there is no equivalent.
However, interface implementations must implement all of their base methods, so forgetting a method will usually give you a compiler error.
This makes it less important.
In the first example it's an interface you're implementing. You can't override something when you're the only implementer in the inheritance chain.
In the second example you've inherited from a concrete implementation and stated that you want to implement the abstract member and the syntax for that (albeit not literally an override as much as an implementation) is the override keyword. However, you are in fact overriding the chain you're a part of because you're implementing it.
So think of the override keyword more in relation to the fact that you're ensuring your implementation gets called instead of the base class when it's called on an instance of the inheritor.
This too explains why you must explicitly call base.Member() inside the override because you've overriden the chain.
Another OO concept to remember is that the same effect can be achieve on methods that aren't abstract or virtual. Members can in fact be hidden and you don't have to specify them with the new keyword.
With that being said it should help abstract for you the idea that these are very much just language features or maybe better said it's just syntax.
In your first example you are implementing an interface. In this case you do not have to specify the override keyword, simply remove it.
Seems like you have a misconception regarding interface implementation vs. inheritance.
Interface implementations are completely different from inheritance. With an interface, you statically (i.e. at compile time) enforce the presence of certain method signatures. Therefore, any keywords like override or the like are just plain wrong in such a context.
Inheritance on the contrary is causing runtime polymorphism through a virtual method table (basically a list of method adresses).
You can see this also from the fact that, in C#, you can implement as many interfaces as you like, whereas multiple inheritance is forbidden.
The reason is that there is a fundamental difference between implementing an interface and overriding a method.
In order to fully implement an interface, you have to provide implementations for all of methods and/or properties but those implementations do not necessarily have to be overrideable in turn. The compiler wants you to be very specific about your intentions when you create a method, because you may have one of a range of behaviours in mind, and it wants to be sure which one you mean.
The override keyword means "I am overriding the base class' implementation with this one". If when implementing an interface, there is no base implementation, then it doesn't apply. You use virtual to indicate an overrideable method with no base implementation, and omit both override and virtual otherwise.
So given this interface:
interface IFoo
{
void Bar();
}
This class implements that interface, and permits classes to inherit from it in turn and override that implementation (since unlike in e.g. Java, methods in C# are not virtual by default):
class Foo : IFoo
{
public virtual void Bar() { ... } // compiles
}
class DerivedFoo : Foo
{
public override void Bar() { ... } // compiles, and may choose to call base.Bar()
}
Whereas this class implements that interface, and does not permit overrides:
class Foo : IFoo
{
public void Bar(); // compiles
}
class DerivedFoo : Foo
{
public override void Bar() { ... } // does NOT compile; Foo.Bar() is not virtual (overrideable)
}
There are in fact more possiblities than that, including:
You can create an abstract base class which implements an interface, but only provide abstract implementations for some/all methods.
You can explicitly implement an interface method
You can seal an overriding method to prevent further overrides
You can create a new method with the same name which is unrelated to the base class' method of that name
There are more details on MSDN.
If you aren't specific enough for the compiler, it will warn you or throw an error.
Update
The reason the compiler complains in the second example above, is that you will not get polymorphic behaviour. That is, if someone has a reference to Foo and calls Bar(), they will get Foo's implementation, not DerivedFoo's. This is because Bar.Foo is not in the virtual method table. Put another way, in C#, the default when compared to Java is that all methods are final unless you say otherwise.
From your comments it sounds like you're trying to get a warning or error in the case where, in my first example above, you then change IFoo by removing the Bar method entirely. (Obviously if you just change the method signature, you'll get a suitable compile error as you'd hope.)
You can achieve this by explicitly implementing the method:
class Foo : IFoo
{
void IFoo.Bar() { ... }
}
Then if the interface changes, you will get a compile error. However, this means derived classes can no longer override Foo's implementation; if you want that behaviour as well, you need:
class Foo : IFoo
{
void IFoo.Bar() { ... }
protected /* or public */ virtual void Bar()
{
IFoo foo = this; // declare rather than cast, to get compile error not runtime exception
foo.Bar();
}
}
You will still get compile errors if you remove the method, both from your explicit and other implementation.
Bear in mind that the explicit implementation is only available to callers with a reference to an IFoo, not a Foo. But if as in the above code you do add a public method which, for example, delegates to the explicit IFoo implementation, that won't be a problem (and it doesn't have to be virtual unless you want it overrideable).
This is an approach that works; whether it's overkill is a matter of taste, but I can see the merit in removing redundant code as part of refactoring, provided the classes are not public and/or not used outside your assembly. However instead of factoring code in this fashion I'd recommend using a tool such as ReSharper which will warn you about unused methods.

create mustoveride function with code in it

I have a MustInherit class with some MustOveride Methods in it. When i inherit form that class, I automatically get the MustOveride Methods or properties.
My question is, I want to be able, to inherit from a class, get my MustOveride functions and methods, but then with some code already in it. I've once seen a .net class that did it, when I inherited from that class, I got the methods, with some comments in it.
Does anybody have an idea what i mean? (It a bit hard to describe ;-) )
I think what you described is known as Template Method Pattern:
public abstract class MyClass
{
public void SomeMethod()
{
// code
MustInherit();
// code
}
protected abstract void MustInherit();
}
Create a method which will not be overridden SomeMethod in this sample and stuff all common code into this class. Then create an abstract method which must be overridden.
If you want to provide a default implementation, so the method must not be overridden but can be use the virtual keyword.
public abstract class MyClass
{
public void SomeMethod()
{
// code
MustInherit();
// code
}
protected virtual void CanInherit()
{
// default implementation
}
}
I assume, you want to do have the following:
When you inherit from that abstract base class, you want to have those abstract methods already partly implemented in your class.
This is not possible out of the box. It could be achieved with some templating, but that has nothing to do with C# or VB.NET but with the IDE used.
The only thing you can do is to create that method as virtual (C# - I don't know how it is called in VB.NET) in the base class and call the base implementation in the derived class.
An Abstract class for you service :)
If you need that consumer of your abstract class ovverides some methods for sure then mark them as abstract too. If you need just to provide possibility of ovveriding you methods but this is not definitely necessary then mark them as virtual.
With the virtual keyword you are not forced to implement the inherited method, then it will use the default implementation of the base class. In that way, you kind of inherit all the code from the base method.
Otherwise, you can implement you own derived version of the method, and somewhere in it call the base class' version of method : base.MethodName(...);. That allow you to kind of inherit all the code from the base method once again, but this time with additional code before and after which is specific to your derived class.
Otherwise, you can make your base class' method such that it uses delegates in its code and call it here and there. Thus the fundamental functioning of the base class' method remain the same for all the derived classes, but each derived class provides its own delegates to adjust some detail key blocks of code in the base class' method.
Otherwise, if you want to see partially implemented methods with comments here and there like Add your code here, it's typically a matter of code generated by an external tool like Visual Studio or another IDE and has nothing to do with the language itself.
But as you see there are plenty of possibilities, depending of you you want precisely...

Categories

Resources