关于C#类中自动属性与私有字段关联及value关键字的疑问
Great questions—let’s break these down one by one, since auto-properties are one of those C# syntax sugars that feel magic until you peek under the hood.
1. How Auto-Properties Link to Implicit Private Fields
First off, your example uses hWorked as the explicit backing field, but when you use an auto-property like public int HoursWorked { get; set; }, the C# compiler handles creating the backing field for you automatically during compilation.
The compiler generates a private, compiler-named field (something like <HoursWorked>k__BackingField—a name you can’t reference directly in your code) to store the property’s value. The auto-property’s get and set accessors are then wired up to read from and write to this hidden field.
In short: the auto-property syntax is just shorthand that tells the compiler, "create a private backing field and wire up basic get/set logic for me". It behaves exactly like writing the explicit field and property yourself—you just don’t have to type all that boilerplate.
2. The value Keyword in Set Accessors
The value keyword is an implicit parameter automatically defined for every set accessor. Its type matches exactly the type of the property (so for int HoursWorked, value is an int).
When you assign a value to the property (e.g., myObject.HoursWorked = 8;), the value on the right side of the equals sign (in this case, 8) is passed into the set accessor as the value parameter. The accessor then assigns that parameter to the backing field—whether it’s the compiler-generated one from an auto-property, or your explicit hWorked field.
Think of it like this: if you wrote the set logic as a separate method, it would look like:
public void SetHoursWorked(int value) { hWorked = value; }
The value keyword is just C#’s way of wrapping this parameter into the property syntax—you don’t have to declare it, it’s always there when you write a set accessor.
内容的提问来源于stack exchange,提问作者Zach

