Search code examples
c#.netvirtualaccess-specifier

C# why we cannot define virtual protected members?


the code below causes the following compilation error:

the modifier virtual is not valid for this item.

Why?

internal class Animal {
    protected virtual string prop; //<- error here: the modifier virtual is not valid for this item
}

On windows docs it implies protected is an allowed keyword (and i see no reason it wouldn't be).

The same question was asked here, but the answer said "the access specifier must match the parent class". In the above example there is no parent class.

I'm using C# 10 on .NET6


Solution

  • In your current code prop is not a property, but a field.
    And fields cannot be virtual:

    The virtual keyword is used to modify a method, property, indexer, or event declaration.

    (emphasis is mine)

    To make it a property, you must supply get and set methods,
    or specify to use their default version, like this:

    internal class Animal
    {
        protected virtual string prop { get; set; } 
    }