Member Access Block #9386
Unanswered
ActivistInvestor
asked this question in
Language Ideas
Replies: 1 comment 3 replies
-
See: #6602 |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Proposal: Member Access Block
Summary
This proposal introduces a new syntactic feature for C#, called the Member Access Block, inspired by Visual Basic’s
With...End With
construct. It allows a concise and expressive way to perform multiple member accesses—assignments, method calls, nested property access—on a single object.The proposal also includes a suggested disambiguating syntax using the member access operator (
.
) followed by a block, i.e.,expr . { ... }
, to avoid parsing conflicts and make the intent clearer.Motivation
C# object initializers are a useful shorthand for property assignment but are currently limited to assignments after a constructor call. Furthermore, they prohibit method calls and deeper member access, which makes them ill-suited as a general-purpose syntax.
This proposal generalizes and expands the object initializer syntax into a more flexible Member Access Block that:
Example
Before
After (Using Member Access Block with
.
Syntax)or:
Semantics and Design
Expression Target
Any valid expression that evaluates to a reference type may be used on the left-hand side of a Member Access Block:
Allowed Member Access Forms
+=
) and unsubscription (-=
)This removes the limitation imposed by compiler error CS0747, which in standard C# prohibits method calls inside object initializers.
Return Value
The block itself returns the result of the expression it is applied to, making it composable:
Syntax Rationale
The inclusion of the
.
(member access operator) before the block disambiguates this syntax from object initializers or collection initializers. It visually and semantically suggests that the block contains member interactions, making it more intuitive and compiler-friendly.Grammar Sketch
Comparison with Visual Basic
With...End With
With...End With
new
expressionsFluent API Comparison
vs.
Potential Drawbacks
Conclusion
The Member Access Block, particularly when introduced with a disambiguating dot (
.
) before the block, offers an elegant and powerful shorthand for multiple member operations on the same object. It improves expressiveness, reduces redundancy, and provides a clear conceptual parallel to Visual Basic’sWith...End With
.Future Considerations
with
keyword for readability:with obj { ... }
Beta Was this translation helpful? Give feedback.
All reactions