Compiler using get and set Methods over BackingFields #2339
Replies: 7 comments
-
The JIT is responsible for optimisations such as inlining. |
Beta Was this translation helpful? Give feedback.
-
There are post compilation tools (one that I've used is PostSharp) that can rewrite property implementations after the compiler has done its job. It would therefore be a breaking change if the C# compiler changed to directly reference the backing field instead of calling the property getter, as any rewritten property getter would be bypassed. |
Beta Was this translation helpful? Give feedback.
-
Also, for future reference this type of issue probably belongs on the Roslyn repo. |
Beta Was this translation helpful? Give feedback.
-
@YairHalberstadt yeah i just noticed this is csharplang. My bad. |
Beta Was this translation helpful? Give feedback.
-
No problem |
Beta Was this translation helpful? Give feedback.
-
IIRC, this is by design, by C# language spec. struct Sample
{
// get-only auto property was introduced in C# 6.0
public int X { get; }
public int Y { get; set; }
public Sample(int x, int y)
{
// All fields must be initialized before accessing function members.
// To allow this property initialization, X = x should be translated into <X>k__BackingField = x.
X = x;
// This could not compile with C# 5.0 or earlier
// but can compile with 6.0 or later due to translation into <Y>k__BackingField = y.
Y = y;
}
} Private access to auto-implemented properties may be allowed to optimized by C# compiler, not by JIT. |
Beta Was this translation helpful? Give feedback.
-
@ufcpp I actually read that as the other way around, the JIT can but the compiler cannot:
For constructors, the spec defines the compiler behaviour you're observing:
|
Beta Was this translation helpful? Give feedback.
-
Maybe my understanding of this is not good enough, but can't the compiler use BackingFields instead of properties within the same class?
E.g. right now, this code
Results in the following compiler generated C# code (according to https://sharplab.io)
But can't the Run-method look like this? (Inlining the get-method)
Am I wrong here or is it just not a big enough deal to change or is the magic happening somewhere else?
Beta Was this translation helpful? Give feedback.
All reactions