Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

There are many times I would love to have an automatic backing field in C#. C# will do that if you use the default setter but in cases where that's not possible I dislike having to both declare a separate field and having it available to the rest of the class outside of the setter.


https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/cs...

edit: the properties reference now documents the 'field' keyword too


That might be all the motivation I need to go move to .NET 9.


.NET 9 has so much good stuff in it. Thing that I randomly realized I wanted only to find out it works in 9 is dictionary access with "related" types (so like if you have a ReadOnlySpan<char> you can use that to find a value from a string in the dictionary via a value type created off the dict).


C# 13 has this via the field keyword (as preview feature): https://learn.microsoft.com/en-us/dotnet/csharp/language-ref...

It's pretty similar to what PHP provides here, except that PHP uses "$this->propname =" and C# uses "field =".

Edit: As someone involved in the RFC, it's somewhat funny, because we considered a special variable like "$field" or "$value" too magic, and C# does just that with a field keyword.


I think it being a keyword does change how magic the feature feels. "$field" and "$this->name" make me think that this behavior is playing by the normal rules of the language but is implemented using some trickery to edit the local scope of this function to add or modify variables. When it's a keyword it says this is a special form and that this is a feature of the language itself.


The `field` keyword also already existed in C#, to add attributes to the backing field of automatic properties, so I think the argument was easier there.

I used it in Unity projects to have serialized/inspectable values exposed through properties:

    [field: SerializeField]
    public int MyProperty { get; private set; }




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: