What if a property declaration was a scope, inside which you could declare additional members - more than just the standard get and set declarations?
As .NET developers, we’re all familiar with the standard C# property declaration and the associated member variable:
Such a feature would allow you to encapsulate the relevant member variable, preventing access except via the properly accessors. It might look like this:
The obvious advantage is in the way it keeps all the related declarations together.
Let’s try a thought experiment and see what happens if we take this idea further.
By treating the property declaration as an arbitrary scope and allowing other declarations, we could create a property that knows if it has been modified:
Here’s a demo showing how this might be used:
What should happen if the name of a subproperty or submethod conflicts with a member that already
exists on the property type? One approach would be to make it a compilation error, but perhaps a
strategy in line with extension methods
where existing members take priority would be good ideas, not least because of its consistency.
Another potential solution would be to use a different operator (perhaps ‘
..’) to keep things
in different scopes.
A big disadvantage of this syntax is that it lacks reusability - code written to provide this functionality for one property can’t be reused for another. This is probably in itself sufficient reason that this would never see the light of day - but it’s an interesting experiment none the less.