Closed
Description
Given code like:
public class C
{
public static A Shared { get; } = new B();
}
public abstract class A { public virtual void Foo(); }
public sealed class B : A { public override void Foo(); }
the compiler currently produces an equivalent for the Shared
property like:
private static readonly A <Shared>k__BackingField = new B();
public static A Shared => <Shared>k__BackingField;
If the backing field were instead created as type B
instead of as A
, e.g.
private static readonly B <Shared>k__BackingField = new B();
public static A Shared => <Shared>k__BackingField;
it would be easier for the JIT to devirtualize calls to C.Shared.Foo();
It seems like the C# compiler could do this fairly easily, using the type of the RHS expression rather than the type of the property, as long as there isn't a conversion/boxing/etc. involved.