3 ms·
C# has the same thing as Properties, but the backing value is set explicitly as a separate variable: https://learn.microsoft.com/en-us/dotnet/csharp/programmin
by Drew_ 2y ago
C# has the same thing as Properties, but the backing value is set explicitly as a separate variable:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/using-properties https://learn.microsoft.com/en-us/dotnet/csharp/programming-...
- wvenable 2y agoThere 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.
- neonsunset 2y agohttps://learn.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-13#the-field-keyword https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/cs... edit: the properties reference now documents the 'field' keyword too
- wvenable 2y agoThat might be all the motivation I need to go move to .NET 9.
- runevault 2y ago.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).
- bwoebi 2y agoC# 13 has this via the field keyword (as preview feature): https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/field 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.
- kroltan 2y agoThe `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; }
- Spivak 2y agoI 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.