Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a virtual method is declared abstract

My friend asks me if an abstract method could have virtual modifier. And I said, No. Because, an abstract method is implicitly also a virtual method, it cannot have the modifier virtual.

But while reading one of the MSDN articles, I have seen this:

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

I can't understand first sentence correctly. Could you please, explain me what they wants to say?

Thanks.

like image 812
Farhad Jabiyev Avatar asked Aug 24 '14 14:08

Farhad Jabiyev


People also ask

Can virtual method be abstract?

Virtual Method can reside in abstract and non-abstract class.

Can we declare virtual method in abstract class?

Answer: Yes, We can have virtual method in an Abstract class in C#. This is true that both virtual and abstract method allow derived classes to override and implement it. But, difference is that an abstract method forces derived classes to implement it whereas virtual method is optional.

Can we declare virtual method in abstract class C#?

Abstract method declarations are only permitted in abstract classes. public abstract void MyMethod(); The implementation is provided by a method override, which is a member of a non-abstract class. It is an error to use the static or virtual modifiers in an abstract method declaration.

Are virtual functions the same as abstract?

You use virtual methods to implement late binding, whereas abstract methods enable you to force the subclasses of the type to have the method explicitly overridden. In this post, I will present a discussion on both virtual and abstract methods and when they should be used.


1 Answers

It becomes clearer when you look at the code example 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 virtual method D.DoWork is inherited by E, and, there, declared abstract. The method is still virtual, it has just become abstract as well.

As you correctly state, an abstract method is always virtual. If your friend is still unconvinced, here's an official quote for that:

An abstract method is implicitly a virtual method.

like image 171
Heinzi Avatar answered Oct 14 '22 06:10

Heinzi