Say I have an interface like interface IThing { virtual string A => "A"; }. What effect does the virtual keyword have on implementing types here? Surprisingly, I couldn't find anything regarding this on either SO, dotnet GitHub pages and discussions, nor on learn.microsoft.com, possibly buried under all the unrelated content where the words interface and virtual appear in any combination. From my quick testing it doesn't appear to have any sensible effect. My intuition tells me to expect from the implementing classes' hierarchy to have been introduced the given virtual members, as if the base implementing class has declared them itself, but it's not the case.
For example:
class Thing: IThing
{
}
class Thing2: Thing
{
override public string A => "!"; // ERROR: No suitable method found to override.
}
If I declare the A property on Thing, but do not declare it explicitly as virtual, it still won't compile. I also have the freedom apparently to just define them w/o the modifier despite it being present in the interface and it compiles. And code using IThing only sees the default implementation of A regardless of what I do unless the class implements the interface directly and not through inheritance in this setup.
Can somebody clarify the use of the virtual modifier on interface members? I use the latest stable language version of C#.
The following:
Is the so called default interface method and virtual as far as I can see actually does nothing because:
I.e. it just an explicit declaration of the fact that interface method is virtual since the language team decided to not restrict such things.
See also the Virtual Modifier vs Sealed Modifier part of the spec:
Note that default implemented
IThing.Ais not part of theThing, hence you can't donew Thing().A, you need to cast to the interface first.If you want to override the
IThing.Ain theThing2then you can implement the interface directly:Another way would be declaring
public virtual string Ain theThingso your current code forThing2works:To understand meaning of
sealed/virtualidentifiers in interfaces you can create a second interface:While if you declare
IThing.AassealedthenIThing2will not compile:Also check out the why virtual is allowed while implementing the interface methods? linked by wohlstad in the comments.