If the virtual method is declared abstract

My friend asks if an abstract method can have a virtual modifier. And I said: No. Since an abstract method is also an implicit virtual method, it cannot have a virtual modifier.

But when reading one of the MSDN articles , I saw this:

... If the virtual method abstract is declared, it is still virtual for any class inheriting from the abstract class. A class that inherits an abstract method cannot access the original implementation of the method — in the previous example, DoWork in class F cannot call DoWork on class D. Thus, an abstract class can force derived classes to provide new methods for virtual methods ....

I cannot correctly understand the first sentence. Could you explain what they want to say?

Thanks.

+5
source share
2 answers

This becomes clearer when you look at the sample code directly above the quoted paragraph:

public class D { public virtual void DoWork(int i) { // Original implementation. } } public abstract class E : D { public abstract override void DoWork(int i); } 

The D.DoWork virtual method D.DoWork inherited by E , and there abstract is declared. The method is still virtual; it has also become abstract.

As you rightly point out, an abstract method is always virtual. If your friend is still not convinced, here is the official quote for this:

An abstract method is implicitly a virtual method.

+6
source

Abstract classes can override virtual members using abstract units:

 public class B { public virtual void M() { } } public abstract class D : B { public abstract override void M(); } public abstract class D2 : D { public override void M() { } } 

The sentence says that D2 should override void M() because it is declared an abstract in D If it was declared as D2 : B , this will be optional, but as it is, D2 must comply with the contracts specified in D , but M() will also behave like any other element overriding the "normal" virtual member, since M() is both virtual and abstract.

+1
source

Source: https://habr.com/ru/post/1201025/


All Articles