@property fields
Quirin Schroll
qs.il.paperinik at gmail.com
Thu Jan 23 03:36:08 UTC 2025
On Thursday, 16 January 2025 at 00:47:47 UTC, Quirin Schroll
wrote:
> This reminds me of [this C#
> proposal](https://github.com/dotnet/csharplang/blob/main/proposals/field-keyword.md). You’re proposing something quite similar, just the other way around. Your idea is to define the backing field and annotate it to request the getter and setter be defined.
>
> TL;DR: The C# proposal adds a contextual `field` keyword that,
> when used in the getter or setter of a property, refers to an
> implicitly generated backing field.
The point of adding auto properties to C# originally was to
provide consistent access (via properties) with the convenience
of a field.
```cs
// Old C#
struct S
{
private int m_X;
public int X { get => m_X; set => m_X = value; }
private string m_y;
public string Y { get => m_Y; set {
ArgumentNullException.ThrowIfNull(value); m_Y = value; } }
}
// Current C#
struct S
{
public X { get; set; }
private string m_y;
public string Y
{
get => m_Y;
set { ArgumentNullException.ThrowIfNull(value); m_Y =
value; }
}
}
```
The point of the C# proposal was to fill the gap where the setter
does some work, but the getter and assignment are fairly trivial.
We need to repeat the type of the property and the name of the
backing field. Also, ideally, we never assign the backing field.
```cs
// Proposed C#
struct S
{
public X { get; set; }
public string Y
{
get => field;
set { ArgumentNullException.ThrowIfNull(value); field =
value; }
}
}
```
The whole point of having the short-hands is to provide an easy
way to write properties that can grow into more elaborate getters
and setters.
This is what IMO, this D proposal lacks. It just makes it easy to
write *trivial* getter and setter functions so that invariants
run. That alone isn’t worth it.
If this mimicked the C# approach, it would also run invariants,
but it would also be possible to write properties that can grow
into more elaborate getters and setters.
Maybe something like:
```d
@property int x auto = 10;
```
In non-interface types, that rewrites to:
```d
private int __x = 10;
@property int x() /* infer attributes */ => __x;
@property void x(int __value) /* infer attributes */ => __x =
__value;
```
In interface types:
```d
@property int x auto pure @safe;
```
It rewrites to:
```d
@property int x() pure @safe;
@property void x(int __value) pure @safe;
```
Then, if one notices more than reading or assignment is needed,
one can expand the `auto` property. A good IDE could do this with
one click. The great thing about that is that the interface does
not change. From the outside, nobody knows if a property is
`auto` or not.
More information about the dip.ideas
mailing list