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.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Azeem AnzariRank #4,413 · 345 reputationPosted Aug 30, 2015, 6:34 PM EDT
Karthikeyan KRank #554 · 4.4K reputationPosted Aug 30, 2015, 7:20 PM EDT
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.Karthikeyan KRank #554 · 4.4K reputationPosted Aug 30, 2015, 7:23 PM EDT
..................................................................................................................................................