roslyn: Proposal: Class-scoped blocks for fields / explicit field usage
Often there are fields in a class that are only used by a few methods or even only one property.
In addition to #850 I suggest adding block syntax for grouping fields to their associated methods only.
public class Person()
{
private _classField_1_;
private _classField_2_;
{ // start scope block
int _age;
public int Age
{
public get => _age;
private set => _age = value >= 0 ? value : 0;
}
public void CelebrateBirthday()
=> _age += 1;
} // end scope block
/* rest of class and further blocks */
}
In this example _age
won’t clutter the IntelliSense and also generate a compiler error if used outside the block accidentially (by older code versions).
It is important that only fields are bound to the block, not the contained methods, properties, subclasses, etc. To make that more verbose prepending the block by a keyword, like var
, could be better
public class Person()
{
var { // start scope block
int _age;
/* ... */
}
/* ... */
}
About this issue
- Original URL
- State: closed
- Created 8 years ago
- Reactions: 4
- Comments: 26 (11 by maintainers)
So for a proposal targeted at the audience of novices and hobbyists who aren’t as familiar with proper programming guidelines, there is a lot of additional necessary syntax required in order to utilize the feature. Syntax that a novice or a hobbyist would not be very likely to know or understand how to use, let alone spend the time and energy planning out. This doesn’t create a pit of success; it creates a mountain.
@lachbaer
The problem with that entire concept is that the very target you intend is also the least likely to actually employ this feature. Someone who slops together a giant monolithic class full of interdependencies isn’t going to take the time to whittle down those dependencies into concrete scoping blocks anymore than they’re likely to refactor that giant class into smaller classes. C# shouldn’t add features which encourage abuse of the language and incorrect design patterns.
In this specific case, I would focus on picking apart the suggested use examples. E.g. consider this refactoring:
I bet any example would most benefit from refactoring to extract new types / functions rather than the suggested language feature.
Like a
class
?