can we override method if its not defined as a virtual in base class???
can we override a method if its not defined as a virtual in base class???
Know the answer? Post it — somebody with the same question will find it here.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Karthikeyan KPosted Aug 30, 2015, 11:23 PM
..................................................................................................................................................
Karthikeyan KPosted Aug 30, 2015, 11:20 PM
No, you cannot override a non-virtual . The closest thing you can do is hide the method by creating a
newmethod with the same name but this is not advisable as it breaks good design principles.But even hiding a method won't give you execution time polymorphic dispatch of method calls like a true virtual method call would. Consider this example:
{{}}{{}}{{}}In this example both calls to the
Mmethod printFoo.M. As you can see this approach does allow you to have a new implementation for a method as long as the reference to that object is of the correct derived type but hiding a base method does break polymorphism.I would recommend that you do not hide base methods in this manner.
I tend to side with those who favor C#'s default behavior that methods are non-virtual by default (as opposed to Java). I would go even further and say that classes should also be sealed by default. Inheritance is hard to design for properly and the fact that there is a method that is not marked to be virtual indicates that the author of that method never intended for the method to be overridden.
Edit: "execution time polymorphic dispatch":
What I mean by this is the default behavior that happens at execution time when you call virtual methods. Let's say for example that in my previous code example, rather than defining a non-virtual method, I did in fact define a virtual method and a true overridden method as well.
If I were to call
b.Fooin that case, the CLR would correctly determine the type of object that thebreference points to asBarand would dispatch the call toMappropriately.Azeem AnzariPosted Aug 30, 2015, 10:34 PM