Search code examples
c#abstract-classmethod-hiding

Abstract methods and hiding methods


I'm trying to understand abstract classes in c# better.

I know that in abstract classes you MUST override abstract methods and MAY override virtual methods..

my question is:

can I override non virtual methods? (I know that normally I can't - but maybe with abstract classes it's different?) or will it be like hiding ?

also, as I read here How to force call a C# derived method (the first answer) - it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never? if so - what is the point of hiding a method?


Solution

  • I'm trying to understand abstract classes in c# better.

    OK, then lets correct your mistakes, because you have some completely wrong ideas about abstract classes here.

    I know that in abstract classes you MUST override abstract methods and MAY override virtual methods.

    Absolutely not; the first part of that sentence is completely wrong. There is no requirement whatsoever in an abstract class to override an abstract method.

    A non-abstract class is called a concrete class. The real rules are:

    • A concrete class must override all abstract methods of all its abstract base classes with concrete methods; it can do so either itself, or via one or more of its base classes.

    This should make sense: you can't make an instance of a concrete class until every abstract method is implemented; otherwise you could invoke a method that has no implementation, and that would be bad.

    • Any derived class may override a non-sealed virtual method of any of its base classes.

    can I override non virtual methods?

    No. You can overload non-virtual methods and you can hide existing non-virtual methods, but you cannot override them.

    it seems to me that because non virtual methods statically linked at compile time and can't be changed - I would not be able to call the methods in the derived class ,never?

    Of course not. You call the methods of the derived class by converting the receiver to the derived class.

    what is the point of hiding a method?

    Duplicate of:

    Is method hiding ever a good idea

    Here's a BONUS QUESTION that you did not ask. See if you can answer it.

    Can a method be marked as both abstract and override? If no, why not? If yes, give an example and explain why you would want to.

    If you can answer that question correctly then you probably have a good understanding of abstract methods. The solution is here.