CS8080 forces pointless override of property accessors #1539
-
class Parent
{
public virtual bool Property { get; set; }
}
class Child : Parent
{
public override bool Property { get; } // CS8080 Auto-implemented properties must override all accessors of the overridden property.
} Besides the uselessness of the that override, why is this not allowed? This is allowed: class Child : Parent
{
private readonly bool field;
public override bool Property { get => field; }
} |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments
-
Why isn't the public bool Property { virtual get; set; } Has this already been discussed? |
Beta Was this translation helpful? Give feedback.
-
What would be the syntax for a derived type extending that accessor? As the property itself is not To IL the properties themselves aren't virtual/sealed, only their accessors are. It doesn't care if one of the accessors is sealed and the other is virtual. But when you override a property the C# compiler also creates another property entry in the derived type, which is where additional metadata goes such as attributes. While you can define that entry with accessors from a base type, the verifier reports the following error:
So, it might be possible to come up with a syntax to override a specific accessor from a base class, but it couldn't smell like a property override because the compiler can't emit additional property metadata. |
Beta Was this translation helpful? Give feedback.
-
This would produce unintended behavior as the backing field is regenerated for var c = new Child();
c.Property = true;
Console.WriteLine(c.Property); // "False" |
Beta Was this translation helpful? Give feedback.
-
I'd be interested if the opposite could become allowed, at least when overriding an public abstract class Parent
{
public abstract bool Property { get; }
}
class Child : Parent
{
public override bool Property { get; internal set; } //currently reports CS0546 'Child.Property.set': cannot override because 'Parent.Property' does not have an overridable set accessor.
} The current alternative is to write an explicit backing field + separate Potential alternative syntax options:
|
Beta Was this translation helpful? Give feedback.
-
@Joe4evr I've written a proposal a long time ago on the Roslyn repository about that. I've now submitted it to this repo: see #1568. |
Beta Was this translation helpful? Give feedback.
This would produce unintended behavior as the backing field is regenerated for
Child
. Aget
operation would callChild.getProperty()
whileset
would callParent.setProperty(value)
and write to the other backing field: