confusion regarding overriding rules C# - c#

I have a litte confusion regarding method overriding and the validity of OOP priciples.
I know everything regarding sealing, shadowing, overriding, virtual etc. but I came across a scenario, that just confused me. Suppose I have:
class classA
{
public virtual void sayhello()
{
Console.WriteLine("hello I'm A");
}
};
class classB :classA
{
public override void sayhello()
{
Console.WriteLine("hello I'm B");
}
};
class Program
{
static void Main(string[] args)
{
classB a = new classB();
a.sayhello();
}
}
According to everything I studied so far, a method declared as virtual or abstract (in abstract class) can be overriden using override keyword in child class. according to this, above code works perfect.
When I remove the virtual keyword, and then try to override the method using override keyword, then compiler gives error as:
cannot override inherited member 'inheritence.classA.sayhello()' because it is not marked virtual, abstract, or override
and then i removed the override key word, from child class, and provided the implementation as:
class classB :classA
{
public void sayhello()
{
Console.WriteLine("hello I'm B");
}
};
In this case, the method could be overrided. I'm able to override the method, which is not virtual or abstract. so, my question is:
1. Did it not violate the OOP principle? since I'm able to override the method, which is not marked as virtual in parent.
2. Why am I allowed to override the method this way? which is not even marked virtual?
3. Removing virtual keyword from classA method, it gave me the feeling of sealed method in classA, when I tried to override that method in classB. (as I mentioned the compiler error earlier). If i remove virtual, so that the child class may not override it, then WHY could the child class cleverly override it, removing its override keyword? Is this ONLY the case, sealed keyword is designed for?

I will like to tell you that you gave hidden the parent child method not overridden.
One more thing you might have not noted doing the same is seeing WARNING because in warning section it will be clearly mentioned that,
Warning 'line number' 'classB .sayhello' hides inherited member 'classA.sayhello'. Use the new
keyword if hiding was intended.
Your question,
Did it not violate the OOP principle? since I'm able to override the method, which is not marked as virtual in parent.
No surely it did not violate the OOP principle as you have hide the base class method.
Why am I allowed to override the method this way? which is not even marked virtual?
Because C# not only supports overriding but also method hiding and A hiding method has to be declared using the new keyword. For More Information read dotnet_polymorphism and overriding-vs-method-hiding
Is this ONLY the case, sealed keyword is designed for?
From MSDN sealed sealed keyword is designed to prevent derivation of class and to negate the virtual aspect of the virtual members.
When applied to a class, the sealed modifier prevents other classes from inheriting from it.
sealed modifier can be only applied to a method or property that overrides a virtual method or property in a base class. This prevent further overriding specific virtual methods or properties but it can never stop method-hiding. Read Non-overridable method for more information

Did it not violate the OOP principle? since I'm able to override the method, which is not marked as virtual in parent.
You did not override the parent method you have hidden the parent method.
so you can never access the parent method from the child class object as it was hidden by your child class method sayhello().
2.Why am I allowed to override the method this way? which is not even marked virtual?
because you can hide the parent methods with child implemetation.

I think this comes from C++ implementation, which used slicing (What is object slicing?).
While C# resembles mostly Java, in some cases (this one and the existence of value types) it follows the C++ way.
The reasoning after this is that, since your code calls method sayhello from an A variable, the programmer expects the logic of A.sayhello to be executed. It does not break OOP principles, since you are executing an A.sayhello implementation (so it must match the A.sayhello contract).
The difference with Java is not OOP vs not OOP, but that Java uses late binding (the actual method to be executed is decided at runtime based in a actual instance) while C# uses early binding (the method is decided at compile time) unless the method is virtual.
Personally I prefer late binding, while C# approach is correct from an OOP point of view, I find that usually the more specialized method should be used.

Well, it's quite simple in the end:
When overriding virtual methods, the concrete methods are resolved at runtime.
When using the new keyword (or leaving it out completely), you're doing a static replacement operation at compile time based on the type information that is available in your code.
These are two totally different things.

What you did is method hiding (as others already explained).
If you really want to do it you should add new keyword in method definition to make warning disappear and also as a documentation. So that other developers looking at your code know that you did it on purpose.

Related

Limit scope of method for child implementations

I hope this isn't a duplicate but I can't find one via Google or SO search. If I want to force the accessibility for a method's implementation of an overridden method to be protected, is my only option to either create as abstract or protected virtual? I know that interfaces specify the declaration but leave the accessibility/scope to the class implementation but I'd like to be sure.
I'd like to know/be certain of if the only way to limit the scope of a method is via a abstract \ protected virtual to give semantics of "this applies to the class implementation or the child override implementation".
A code sample to illustrate. I know I can do the following and limit the scope of an implementation like so;
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
By doing the above I guarantee that child implementations can only override OnlyMeorChildrenCanDoAction()as protected but not public.
But is there another way of limiting to protected without resorting to abstract or protected virtual? An example of creating a method like this is Object.Finalize() as seen here.
Or, to invert the question somewhat, why would you create a method as protected virtual unless to ensure that any implementations were limited in scope? Or is there another way to do the same?
I think you're misunderstanding the meaning and use of virtual. You can only override a method in the parent class if it is declared virtual. The override method in the child class must have the same visibility as the method in the parent class.
Implementations of methods declared in interfaces are always public.
Declaring a method abstract has the same effect as declaring it virtual, except you do not implement it in your class and any concrete classes that derive from your class must implement it.
Technically, the compiler will not allow you to change the access modifiers of a method when overriding it from the parent, so the answer to the question is that by declaring a method as protected within a class, you are only making it available to derived classes (whether abstract or not is a separate concern and doesn't bear on the access level).
Keep in mind, however, that derived class would be free to expose the function in some other way such as calling the protected method from a public one and there is no way to prevent that.
As far as "why" you would have a protected abstract member, a great example can be seen in many implementations of the Template Method pattern. You may have an abstract base class that describes the structure of an algorithm and leave the specific steps of what happens inside the boundary of each step to derived classes. In this case, one way to implement would be to declare the base class as abstract, have a public method serve as the "entry point" for the algorithm, and define specific methods used within the algorithm as protected abstract methods to lay out what the responsibility of derived classes will be. This pattern does a nice job of leaving public only those things that are intended to be consumed by the world, but can present some challenges from a unit testing perspective which are sometimes addressed by raising the visibility of the helper methods from protected to internal.
You cannot use the c# language to prevent a derived class from implementing a public version of OnlyMeOrChildrenCanDoAction. Even if you mark it as protected virtual, the derived class can use the new keyword to cover the method and change its accessibility. For example:
public class BaseClass
{
protected virtual void OnlyMeOrChildrenCanDoAction()
{
// leave empty as current class is structural/conceptual
// but child instances may need it
}
}
public class DerivedClass : BaseClass
{
public new void OnlyMeOrChildrenCanDoAction()
{
Console.WriteLine("This is public.");
}
}
public class Program
{
public static void Main()
{
var b = new BaseClass();
//b.OnlyMeOrChildrenCanDoAction(); //Will not compile
var d = new DerivedClass();
d.OnlyMeOrChildrenCanDoAction(); //Look! It's public!
}
}
Output:
This is public.
Code available on DotNetFiddle.
If you want to protect the caller from calling OnlyMeOrChildrenCanDoAction, your best bet is for the caller to use only interfaces. If OnlyMeOrChildrenCanDoAction isn't in the interface, there is no way a caller could call it, even if a derived class decided to expose it as a public class member. This is good SOLID design anyway.
On the other hand, if you're not so much worried about the caller as you are worried about your own development team doing bad things, perhaps your best option is to use FxCop or some other source code rules engine integrated into your continuous build process. Developers could still add the method but you could set up a rule to cause it to fail the build if they do so.

Why "New" Keyword in C# [duplicate]

I was looking at this blog post and had following questions:
Why do we need the new keyword, is it just to specify that a base class method is being hidden. I mean, why do we need it? If we don't use the override keyword, aren't we hiding the base class method?
Why is the default in C# to hide and not override? Why have the designers implemented it this way?
Good questions. Let me re-state them.
Why is it legal to hide a method with another method at all?
Let me answer that question with an example. You have an interface from CLR v1:
interface IEnumerable
{
IEnumerator GetEnumerator();
}
Super. Now in CLR v2 you have generics and you think "man, if only we'd had generics in v1 I would have made this a generic interface. But I didn't. I should make something compatible with it now that is generic so that I get the benefits of generics without losing backwards compatibility with code that expects IEnumerable."
interface IEnumerable<T> : IEnumerable
{
IEnumerator<T> .... uh oh
What are you going to call the GetEnumerator method of IEnumerable<T>? Remember, you want it to hide GetEnumerator on the non-generic base interface. You never want that thing to be called unless you're explicitly in a backwards-compat situation.
That alone justifies method hiding. For more thoughts on justifications of method hiding see my article on the subject.
Why does hiding without "new" cause a warning?
Because we want to bring it to your attention that you are hiding something and might be doing it accidentally. Remember, you might be hiding something accidentally because of an edit to the base class done by someone else, rather than by you editing your derived class.
Why is hiding without "new" a warning rather than an error?
Same reason. You might be hiding something accidentally because you've just picked up a new version of a base class. This happens all the time. FooCorp makes a base class B. BarCorp makes a derived class D with a method Bar, because their customers like that method. FooCorp sees that and says hey, that's a good idea, we can put that functionality on the base class. They do so and ship a new version of Foo.DLL, and when BarCorp picks up the new version, it would be nice if they were told that their method now hides the base class method.
We want that situation to be a warning and not an error because making it an error means that this is another form of the brittle base class problem. C# has been carefully designed so that when someone makes a change to a base class, the effects on code that uses a derived class are minimized.
Why is hiding and not overriding the default?
Because virtual override is dangerous. Virtual override allows derived classes to change the behaviour of code that was compiled to use base classes. Doing something dangerous like making an override should be something you do consciously and deliberately, not by accident.
If the method in the derived class is preceded with the new keyword, the method is defined as being independent of the method in the base class
However if you don't specify either new or overrides, the resulting output is the same as if you specified new, but you will get a compiler warning (as you may not be aware that you are hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).
So it helps you to avoid mistakes and explicitly show what you want to do and it makes more readable code, so one can easily understand your code.
It is worth noting that the only effect of new in this context is to suppress a Warning. There is no change in semantics.
So one answer is: We need new to signal to the compiler that the hiding is intentional and to get rid of the warning.
The follow up question is: If you won't / can't override a method, why would you introduce another method with the same name? Because hiding is in essence a name-conflict. And you would of course avoid it in most cases.
The only good reason I can think of for intentional hiding is when a name is forced upon you by an interface.
In C# members are sealed by default meaning that you cannot override them (unless marked with the virtual or abstract keywords) and this for performance reasons. The new modifier is used to explicitly hide an inherited member.
If overriding was default without specifying the override keyword, you could accidentally override some method of your base just due to the name equality.
.Net compiler strategy is to emit warnings if something could go wrong, just to be safe, so in this case if overriding was default, there would have to be a warning for each overriden method - something like 'warning: check if you really want to override'.
My guess would mainly be due to the multiple interface inheritance. Using discreet interfaces it would be very possible that two distinct interfaces use the same method signature. Allowing the use of the new keyword would allow you to create these different implementations with one class, instead of having to create two distinct classes.
Updated ... Eric gave me an idea on how to improve this example.
public interface IAction1
{
int DoWork();
}
public interface IAction2
{
string DoWork();
}
public class MyBase : IAction1
{
public int DoWork() { return 0; }
}
public class MyClass : MyBase, IAction2
{
public new string DoWork() { return "Hi"; }
}
class Program
{
static void Main(string[] args)
{
var myClass = new MyClass();
var ret0 = myClass.DoWork(); //Hi
var ret1 = ((IAction1)myClass).DoWork(); //0
var ret2 = ((IAction2)myClass).DoWork(); //Hi
var ret3 = ((MyBase)myClass).DoWork(); //0
var ret4 = ((MyClass)myClass).DoWork(); //Hi
}
}
As noted, method/property hiding makes it possible to change things about a method or property which could not be readily changed otherwise. One situation where this can be useful is allowing an inherited class to have read-write properties which are read-only in the base class. For example, suppose a base class has a bunch of read-only properties called Value1-Value40 (of course, a real class would use better names). A sealed descendant of this class has a constructor that takes an object of the base class and copies the values from there; the class does not allow them to be changed after that. A different, inheritable, descendant declare a read-write properties called Value1-Value40 which, when read, behaves the same as the base class versions but, when written, allows the values to be written. The net effect will be that code which wants an instance of the base class that it knows will never change can create a new object of the read-only class, which can copy data from a passed-in object without having to worry whether that object is read-only or read-write.
One annoyance with this approach--perhaps someone can help me out--is that I don't know of a way to both shadow and override a particular property within the same class. Do any of the CLR languages allow that (I use vb 2005)? It would be useful if the base class object and its properties could be abstract, but that would require an intermediate class to override the Value1 to Value40 properties before a descendant class could shadow them.

Abstract Method in Non Abstract Class

I want to know the reason behind the design of restricting Abstract Methods in Non Abstract Class (in C#).
I understand that the class instance won't have the definition and thus they wont be callable, but when static methods are defined,they are excluded from the instance too. Why abstract methods are not handled that way, any specific reason for the same?
They could be allowed in concrete class and the deriving class can be forced to implement methods, basically that is what, is done in case of abstract methods in an abstract class.
First, I think that what you're asking doesn't logically make sense. If you have an abstract method, it basically means that the method is unfinished (as #ChrisSinclair pointed out). But that also means the whole class is unfinished, so it also has to be abstract.
Or another way to put it: if you had an abstract method on a class that wasn't abstract, that would mean you had a method that cannot be called. But that means the method is not useful, you could remove it and it would all work the same.
Now, I'll try to be more concrete by using an example: imagine the following code:
Animal[] zoo = new Animal[] { new Monkey(), new Fish(), new Animal() };
foreach (Animal animal in zoo)
animal.MakeSound();
Here, Animal is the non-abstract base class (which is why I can put it directly into the array), Monkey and Fish are derived from Animal and MakeSound() is the abstract method. What should this code do? You didn't state that clearly, but I can imagine few options:
You can't call MakeSound() on a variable typed as Animal, you can call it only using a variable typed as one of the derived classes, so this is a compile error.
This is not a good solution, because the whole point of abstract is to be able to treat instances of derived classes as the base class, and still get behaviour that's specific to the derived class. If you want this, just put a normal (no abstract, virtual or override) method into each derived class and don't do anything with the base class.
You can't call MakeSound() on an object whose runtime type is actually Animal, so this is a runtime error (an exception).
This is also not a good solution. C# is a statically typed language and so it tries to catch errors like “you can't call this method” at compile time (with obvious exceptions like reflection and dynamic), so making this into a runtime error wouldn't fit with the rest of the language. Besides, you can do this easily by creating a virtual method in the base class that throws an exception.
To sum up, you want something that doesn't make much sense, and smells of bad design (a base class that behaves differently than its derived classes) and can be worked around quite easily. These are all signs of a feature that should not be implemented.
So, you want to allow
class C { abstract void M(); }
to compile. Suppose it did. What do you then want to happen when someone does
new C().M();
? You want an execution-time error? Well, in general C# prefers compile-time errors to execution-time errors. If you don't like that philosophy, there are other languages available...
I think you've answered your own question, an abstract method isn't defined initially. Therefore the class cannot be instanciated. You're saying it should ignore it, but by definition when adding an abstract method you're saying "every class created from this must implement this {abstract method}" hence the class where you define the abstract class must also be abstract because the abstract method is still undefined at that point.
The abstract class may contain abstract member. There is the only method declaration if any method has an abstract keyword we can't implement in the same class. So the abstract class is incompleted. That is why the object is not created for an abstract class.
Non-abstract class can't contain abstract member.
Example:
namespace InterviewPreparation
{
public abstract class baseclass
{
public abstract void method1(); //abstract method
public abstract void method2(); //abstract method
public void method3() { } //Non- abstract method----->It is necessary to implement here.
}
class childclass : baseclass
{
public override void method1() { }
public override void method2() { }
}
public class Program //Non Abstract Class
{
public static void Main()
{
baseclass b = new childclass(); //create instance
b.method1();
b.method2();
b.method3();
}
}
}
You can achieve what you want using "virtual" methods but using virtual methods can lead to more runtime business logic errors as a developer is not "forced" to implement the logic in the child class.
I think there's a valid point here. An abstract method is the perfect solution as it would "enforce" the requirement of defining the method body in children.
I have come across many many situations where the parent class had to (or it would be more efficient to) implement some logic but "Only" children could implement rest of the logic"
So if the opportunity was there I would happily mix abstract methods with complete methods.
#AakashM, I appreciate C# prefers compile time errors. So do I. And so does anybody. This is about thinking out-of-the-box.
And supporting this will not affect that.
Let's think out of the box here, rather than saying "hurrah" to big boy decisions.
C# compiler can detect and deny someone of using an abstract class directly because it uses the "abstract" keyword.
C# also knows to force any child class to implement any abstract methods. How? because of the use of the "abstract" keyword.
This is pretty simple to understand to anyone who has studied the internals of a programming language.
So, why can't C# detect an "abstract" keyword next to a method in a normal class and handle it at the COMPILE TIME.
The reason is it takes "reworking" and the effort is not worth supporting the small demand.
Specially in an industry that lacks people who think out of the boxes that big boys have given them.
It's still not clear why you would want that, but an alternative approach could be to force derived classes to provide a delegate instance. Something like this
class MyConcreteClass
{
readonly Func<int, DateTime, string> methodImpl;
// constructor requires a delegate instance
public MyConcreteClass(Func<int, DateTime, string> methodImpl)
{
if (methodImpl == null)
throw new ArgumentNullException();
this.methodImpl = methodImpl;
}
...
}
(The signature string MethodImpl(int, DateTime) is just an example, of course.)
Otherwise, I can recommend the other answers to explain why your wish probably isn't something which would make the world better.
So the answers above are correct: having abstract methods makes the class inherently abstract. If you cannot instance part of a class, then you cannot instance the class itself. However, the answers above didn't really discuss your options here.
First, this is mainly an issue for public static methods. If the methods aren't intended to be public, then you could have protected non-abstract methods, which are allowed in an abstract class declaration. So, you could just move these static methods to a separate static class without much issue.
As an alternative, you could keep those methods in the class, but then instead of having abstract methods, declare an interface. Essentially, you have a multiple-inheritance problem as you want the derived class to inherit from two conceptually different objects: a non-abstract parent with public static members, and an abstract parent with abstract methods. Unlike some other frameworks, C# does permit multiple inheritance. Instead, C# offers a formal interface declaration that is intended to fill this purpose. Moreover, the whole point of abstract methods, really, is just to impose a certain conceptual interface.
I have a scenario very similar to what the OP is trying to achieve. In my case the method that I want to make abstract would be a protected method and would only be known to the base class. So the "new C().M();" does not apply because the method in question is not public. I want to be able to instantiate and call public methods on the base class (therefore it needs to be non-abstract), but I need these public methods to call a protected implementation of the protected method in the child class and have no default implementation in the parent. In a manner of speaking, I need to force descendants to override the method. I don't know what the child class is at compile time due to dependency injection.
My solution was to follow the rules and use a concrete base class and a virtual protected method. For the default implementation, though, I throw a NotImplementedException with the error "The implementation for method name must be provided in the implementation of the child class."
protected virtual void MyProtectedMethod()
{
throw new NotImplementedException("The implementation for MyProtectedMethod must be provided in the implementation of the child class.");
}
In this way a default implementation can never be used and implementers of descendant implementations will quickly see that they missed an important step.

C# virtual keyword

Is a virtual method compulsory to override by its subclass?
If a method is not virtual (or abstract), it can't be overriden in the sub class. The only option then is to use the new keyword to hide the inherited method, but this is generally not a recommended practice, since casting the instance of the sub class to the parent class and calling the method will cause the parent class method to be called instead, and that is probably not the intended functionality.
So in short, yes it needs to be virtual to override, but no you dont have to override it. If you don't, the base class version will be called instead. But if you do override it, even if you cast the object to it base class type, the derived version of the method will be called, unlike for hiding the method with new.
It's good to know the difference between overriding and hiding the method, since at first glance, and if you test it, it might look like it does the same thing, but will come back to bite you later when the program don't work as expected, and you have no idea why.
No, when you are using "virtual" keyword, it's up to you whether you want to override or not. When you use "abstract", you need to override the method in the derived class. For more information, please see:
virtual (C#) (the keyword)
abstract (C#) (the modifier)
No. It can be overriden by a sub class, but does not have to be.
If you want to enforce overriding by subclasses, use abstract in an abstract class, or use an interface (meaning you have to implement all declared members).
Is a virtual method is compulsory to override by it's sub class?
No.
Can I Override a method which is NON-Virtual in parent class ?
No.
What is YES then ?
You must implement Abstract method of parent class (if derived class is non-abstract)
Can I write Virtual keyword on Static method
NO, Because these two are just opposite words. Virtual means compiler does not know at compile time which method to be called. Static means , for sure , your compiler knows which method will be called.
How do I stop my current class' subclasses to no Override my method ?
Mark it with sealed keyword.
Is Abstract method a virtual also ?
YES. That's why we cant explicitly mark abstract method virtual as well.
Is Override and Overload same ?
Off-course not! Overloading is having 2 methods with same name but which works on different set of input parameters.
When shall I Mark a method as Virtual ?
When you are using polymorphism and you are not sure about the type of the object passes to your method until runtime, and you want your subclasses to have different behavior then mark the method as Virtual.
e.g. You have
class Law
{
public void Punish(Minister any)
{
if (any.Corruption() == true)
{
... do whatever public wants...
}
}
}
And you have Hierarchy of Minister classes -Ministers, CentralGOVTMinisters , StateGOVTMinisters , DistrictAuthorityMinisters etc. And you know that Whatever defined in Minister class for Corruption() method can be used by many derived class but for few ministers Corruption laws are different (they have supreme powers may be !) , so there you override the Corruption() and everywhere else your derived classes use the implementation of Corruption() in Minister class (base of all minister).
Yes, if a method is not marked virtual or abstract it cannot be overridden. The only exception is when declaring an interface method you don't need to use it because an interface method is virtual by definition. When you implement this interface you need to use virtual or abstract if you want to be able to derive from the class implementing the interface and be able to override the method.
It is not compulsory to override virtual methods that are not abstract.
It is compulsory to implement abstract methods unless you also mark your class abstract.
No, it is not mandatory to override a virtual method in a derived class.
yes to override you need to write virtual keyword. or write keyword abstract method.
No, it just means that you can override it, not that you have to. Abstract is the keyword if you want to make it mandatory for the subclass to implement it.

How to "properly" override a base class method?

Whenever i override a method of a base class, other than my implementation of this method, i seem to have 3 choices.
1) Call base.Method(), and then provide my implementation.
2) Provide my implementation and then call base.Method()
3) Just provide my implementation.
Recently while using a library i have realized few bugs that were introduced because of not implementing the method as expected by the library. I am not sure if that is bad on part of library, or something wrong in my understanding.
I will take one example.
public class ViewManager {
public virtual void Customize(){
PrepareBaseView();
}
}
public class PostViewManager {
public override void Customize(){
base.Customize();
PreparePostView();
}
}
public class PreViewManager {
public override void Customize(){
PreparePreView();
base.Customize();
}
}
public class CustomViewManager {
public override void Customize(){
PrepareCustomView();
}
}
My question here is that how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
how could a child class know (without taking a look at base class implementation) which order (or option) is being expected by the parent class?
There is no way to "know" this when you are subclassing and overriding a method. Proper documentation is really the only option here.
Is there a way in which parent class could enforce one of the three alternates to all the deriving classes?
The only option here is to avoid the issue. Instead of allowing the subclass to override the method, it can be declared non-virtual, and call a virtual method in the appropriate place. For example, if you want to enforce that subclasses "call your version first", you could do:
public class BaseClass {
public void Method() // Non-virtual
{
// Do required work
// Call virtual method now...
this.OnMethod();
}
protected virtual void OnMethod()
{ // Do nothing
}
}
The subclasses can then "override" OnMethod, and provide functionality that happens after "method"'s work.
The reason this is required is that virtual methods are designed to allow a subclass to completely replace the implementation of the parent class. This is done on purpose. If you want to prevent this, it's better to make the method non-virtual.
This is why I feel virtual methods are dangerous when you ship them in a library. The truth is you never really know without looking at the base class, sometimes you have to fire up reflektor, read documentation or approach it with trial and error.
When writing code myself I've always tired to follow the rule that says:
Derived classes that override the protected virtual method are not required to call the base class implementation. The base class must continue to work correctly even if its implementation is not called.
This is taken from http://msdn.microsoft.com/en-us/library/ms229011.aspx, however this is for Event design though I believe I read this in the Framework Design Guidelines book (http://www.amazon.com/Framework-Design-Guidelines-Conventions-Libraries/dp/0321246756).
However, this is obviously not true, ASP.NET web forms for example require a base call on Page_Load.
So, long and short, it varies and unfortunately there is no instant way of knowing. If I'm in doubt I will omit the call initially.
The short answer is no. You can't enforce in what order the child calls the base method, or if it calls it at all.
Technically this information should be included in the base object's documentation. If you absolutely must have some code run before or after the child class' code than you can do the following:
1) Create a non-virtual function in the base class. Let's call it MyFunction
2) Create a protected virtual function in the base class. Let's call it _MyFunction
3) Have deriving classes extend the _MyFunction method.
4) Have MyFunction call _MyFunction and run the code it needs to run before or after calling it.
This method is ugly and would require a lot of extra code, so I recommend just putting a notice in the documentation.
The requirements of the base class should be documented by the library designer.
This issue is the reason why some libraries contain mainly sealed classes.

Categories