0

Consider the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace TestApp
{
    interface IMammalClass
    {
        string Speak();
    }

    public abstract class absMammalClass : IMammalClass
    {
        public abstract string Speak();
    }

    public class basePetClass : absMammalClass
    {
        public virtual override string Speak()
        {
            return "Make Noise";
        }
    }

    public class DogClass : basePetClass
    {
        public override string Speak()
        {
            return "Bark";
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            DogClass spot = new DogClass();
            Console.Out.WriteLine(spot.Speak());
        }
    }
}

When I attempt to compile the code I get an "override cannot be marked as new or virtual" error with the "public virtual override string Speak()" method. I understand there are ways around it, but I'm wondering what the reasoning is behind C# not allowing virtuals to override abstracts.

  • 2
    Let me ask you a different question: what are you trying to achieve by marking it `virtual` in that scenario? – MarcinJuraszek Feb 21 '17 at 14:13
  • 1
    `Speak()` is already a *virtual* method – Dmitry Bychenko Feb 21 '17 at 14:14
  • The intent would be to allow classes inheriting basePetClass the option of either overriding or using base.Speak(). absMammalClass either doesn't know or doesn't care how Speak() is implemented, but basePetClass needs to offer a default definition. – arcadebench Feb 21 '17 at 14:23
  • see also http://stackoverflow.com/questions/391483/what-is-the-difference-between-an-abstract-function-and-a-virtual-function – Ian Ringrose Feb 21 '17 at 14:27

2 Answers2

8

A method that overrides its base method is implicitly virtual (unless specified otherwise with the sealed keyword), you don't need to specify it.

Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • In conclusion, removing the keyword "virtual" from the code above allows it to compile. – arcadebench Feb 21 '17 at 14:45
  • Exactly! For a method (or property etc.) _without_ the `override` modifier, the default is a sealed behavior, and you need the `virtual` keyword to change that. However, for a method which has the `override` modifier, the default behavior is an overridable method, and then you need the additional keyword `sealed` to change that. On the method (, property etc.) level, `sealed` occurs only together with `override`. – Jeppe Stig Nielsen Jul 30 '18 at 09:08
3

From MSDN

  • An abstract method is implicitly a virtual method.
  • Abstract method declarations are only permitted in abstract classes.
  • The implementation is provided by an overriding method.
  • Abstract method also can be overridden in an abstract class.
Pavel
  • 616
  • 1
  • 7
  • 13