-
Notifications
You must be signed in to change notification settings - Fork 5.3k
Description
Note: the proposed API was modified significantly during API design review.
See notes below: #34978 (comment)
The type will be used as a modreq on the return type of the set accessor:
public modreq(typeof(IsExternalInit) void set_InitOnlyProperty(string value) { ... }
Out-of-date:
As part of the C# 9 records feature, we want to allow some properties to be settable during "initialization". Initialization means construction and also object creation. So we would allow new C() { InitOnlyProperty = "hello" }.
To declare such a property, we'll allow the following syntax:
public string InitOnlyProperty
{
get { ... }
init { ... } // this is an init-only setter
}We will emit this property as:
// pseudo code
private readonly string backingField;
[InitOnly]
public void InitOnlyProperty_setAccessor(modreq(typeof(InitOnlyAttribute)) string value) { ... }
The attribute is used on the set accessor and in a modreq.
There are two potential expansion of the feature: init-only fields and init-only methods. We can discuss whether it is better to include those now, or add later.
So we are proposing to add the following API:
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public sealed class InitOnlyAttribute : Attribute
{
}
}Updates:
- removed AttributeTargets.Method, added AttributeTargets.Field (jcouv)
- removed [InitOnly] attribute on backing field of auto-property (jcouv)
- added AttributeTargets.Method back, with explanation (jcouv)
- added [InitOnly] on set accessor (jcouv)