Skip to content

Commit

Permalink
Field-backed properties: readonly backing field (#74922)
Browse files Browse the repository at this point in the history
  • Loading branch information
cston authored Aug 29, 2024
1 parent b8c1ea0 commit 10f9b1e
Show file tree
Hide file tree
Showing 2 changed files with 378 additions and 91 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -172,15 +172,34 @@ protected SourcePropertySymbolBase(
{
Debug.Assert(!IsIndexer);
string fieldName = GeneratedNames.MakeBackingFieldName(_name);
BackingField = new SynthesizedBackingFieldSymbol(this,
fieldName,
// Synthesized backing field for 'field' should not be marked 'initonly'
// since the field might be modified in the get accessor.
// PROTOTYPE: Should the backing field be 'initonly' when the containing
// type, property, or accessor is declared 'readonly'?
isReadOnly: !usesFieldKeyword && ((hasGetAccessor && !hasSetAccessor) || isInitOnly),
this.IsStatic,
hasInitializer);

// The backing field is readonly if any of the following holds:
// - The containing type is declared readonly and the property is an instance property.
bool isReadOnly;
if (!IsStatic && containingType.IsReadOnly)
{
isReadOnly = true;
}
// - The property is declared readonly.
else if (HasReadOnlyModifier)
{
isReadOnly = true;
}
// - The property has no set accessor (but may have an init accessor) and
// the get accessor, if any, is automatically implemented.
else if ((!hasSetAccessor || isInitOnly) && (!hasGetAccessor || hasAutoPropertyGet))
{
isReadOnly = true;
}
else
{
// PROTOTYPE: We could treat the field as readonly if all manually implemented get and set
// accessors are declared readonly. Although, to do so, we might need to bind the accessor
// declarations before creating the backing field. See FieldKeywordTests.ReadOnly_05().
isReadOnly = false;
}

BackingField = new SynthesizedBackingFieldSymbol(this, fieldName, isReadOnly: isReadOnly, this.IsStatic, hasInitializer);
}

if (hasGetAccessor)
Expand Down
Loading

0 comments on commit 10f9b1e

Please sign in to comment.