10

Am I correct that declaring a method abstract automatically makes it virtual?

That is, in subclasses I can override it many times and at runtime, the method corresponding to the runtime type of the object will be called?

Is it possible to declare an abstract non-virtual method? That is, the method which must be implemented in a non-abstract subclass and can not be overridden?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Oleg Vazhnev
  • 23,239
  • 54
  • 171
  • 305
  • possible duplicate of [Is every abstract function virtual in C#, in general?](http://stackoverflow.com/questions/391557/is-every-abstract-function-virtual-in-c-in-general) – Jörg W Mittag Jun 10 '12 at 14:51

2 Answers2

12

Yes, abstract methods are virtual by definition; they must be overridable in order to actually be overridden by subclasses:

When an instance method declaration includes an abstract modifier, that method is said to be an abstract method. Although an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.

Conversely you can't declare an abstract non-virtual method, because if you could, you would have a method that can't be implemented and thus can never be called, making it rather useless.

However, if you want to have a class implement an abstract method but not allow any of its subclasses to modify its implementation, that's where sealed comes in. An example:

abstract public class AbstractClass
{
    abstract public void DoSomething();
}

public class BaseClass : AbstractClass
{
    public sealed override void DoSomething()
    {
        Console.WriteLine("Did something");
    }
}

Notice that while the abstract method is (implicitly) virtual, the implementation in the concrete base class is non-virtual (because of the sealed keyword).

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
2

Yes, they are virtual. Otherwise you would have no way to write implementation for them.

0lukasz0
  • 3,155
  • 1
  • 24
  • 40