In C#, why should a class expose GuestName as a property rather than a public field, even when the property only stores a value?
answer
- accessor methods, not storage
- get_GuestName and set_GuestName
- validation later, callers untouched
- compiled callers and MissingFieldException
- ref arguments need a variable
basics
~20 sA property is a pair of accessor methods over a backing field, so validation, computed values or different storage can come later without touching callers; turning a public field into a property later breaks already-compiled callers.
solid answer
~50 sAn auto-property such as `public string GuestName { get; set; }` compiles to `get_GuestName` and `set_GuestName` methods plus a hidden private backing field, and callers bind to those methods, not to the storage. That indirection lets you add validation, compute the value or move the storage later without touching callers, and it offers what a field cannot: a `private` or `init` setter, `virtual`, a place in an interface. The reverse move is not free: a caller compiled against a field emits a direct field access, so replacing the field with a property makes that caller throw `MissingFieldException` until it is recompiled, and source that passed the field by `ref` stops compiling (CS0206). So public data starts life as a property and fields stay private; the .NET design guidelines' exceptions are constants and `static readonly` fields for predefined instances.
code
csharp · 9 linesvar booking = new HotelBooking();
Interlocked.Increment(ref booking.NightsField); // compiles: a field is a variable
Interlocked.Increment(ref booking.Nights); // error CS0206: a property is two methods
public class HotelBooking
{
public int NightsField;
public int Nights { get; set; }
}go deeper
Recall that a property is a get and set accessor pair over a backing field, and that public data is exposed as properties while fields stay private.
Explain what an auto-property compiles to, the accessor methods and the hidden backing field, and why that lets validation, computed values or new storage arrive without touching callers.
Show that a field-to-property swap breaks compiled consumers with MissingFieldException and breaks ref call sites with CS0206, so a shared library has to treat it as a breaking release.
Treat public fields as a contract that cannot evolve: a few accessor declarations today cost far less than coordinating a rebuild of every consumer of a shared package later.
## What the compiler generates A **field** is a variable declared directly in a class or struct: callers that read or write it touch the storage itself. A **property** looks the same from the call site (`booking.GuestName = "Ana Ruiz"`), but it is a member made of **accessors**, small methods the compiler emits as `get_GuestName` and `set_GuestName`. An **auto-property**, `public string GuestName { get; set; }`, is the shortest form. The compiler: - creates a private, hidden **backing field** (its metadata name is `<GuestName>k__BackingField`, which C# source cannot spell); - implements `get` to return that field and `set` to store `value` in it; - lets you target the backing field with an attribute through `[field: ...]` on the property. So even the simplest property is already a method call boundary. Callers depend on the accessor *signatures*, not on where or how the value is kept. ## What a property can do that a field cannot Because callers go through accessors, the class keeps control of the member's behaviour: - **Validation**: a `set` accessor can reject a blank guest name with `ArgumentException`. - **Narrower writes**: `private set`, an `init` accessor (C# 9) or no setter at all, while reads stay public. - **Computed values**: `public int Nights => (CheckOut.DayNumber - CheckIn.DayNumber);` stores nothing. - **Polymorphism and contracts**: a property can be `virtual`, `abstract` or declared in an interface; an instance field can be none of these. - **Change of storage**: the value can move into a dictionary, a lazy cache or another object without callers noticing. Validation, computed values and a change of storage can be added to an existing property without changing a single caller's source or binary, because the accessor methods keep their names and signatures. Narrowing the setter later is different: callers that assign the property stop compiling, so decide on `init` or `private set` up front. ## Why turning a field into a property later is a breaking change Teams often start with `public string GuestName;` and promise to "make it a property when we need validation". The swap looks harmless, but it breaks in three places: 1. **Binary compatibility.** A caller compiled against the field contains an instruction that loads the field `GuestName` directly. After the library ships a property instead, no such field exists, and the old caller fails at run time with `System.MissingFieldException: Field not found` until it is recompiled. 2. **`ref` and `out` arguments.** A field is a variable, so `Interlocked.Increment(ref booking.NightsField)` compiles. A property is two methods with no location to point at, so the same call on a property is error CS0206, "A non ref-returning property or indexer may not be used as an out or ref value". 3. **Struct-typed members.** Writing to a member of a struct reached through a property assigns into a temporary copy and is rejected with CS1612; the copy semantics behind that belong with the material on value and reference copying. Plain reads and assignments recompile unchanged, which is why the break is easy to miss until a consumer that was not rebuilt runs. | | Public field | Property | |---|---|---| | What callers bind to | the storage location | `get_X` / `set_X` methods | | Add validation later | breaks compiled callers | invisible to callers | | `private set` / `init` / read-only | `readonly` only | all of them | | `virtual`, `abstract`, implements an interface member | no (instance fields) | yes | | Pass as `ref` / `out` | yes | no (CS0206) unless ref-returning | ## Where fields are still the right tool Fields are not wrong; **public** instance fields are. The .NET design guidelines say not to expose public or protected instance fields, and carve out two cases: - `const` fields for values that genuinely never change; - `public static readonly` fields for predefined instances of the type. Inside the class, private fields remain the normal way to hold state that a property, an indexer or several methods share. When a property needs logic, it can wrap an explicit private field, or, from C# 14, name its synthesized backing field with the `field` keyword. ## What to say in an interview - A property is an API made of methods; a field is storage. - Start public data as an auto-property: it costs one line and keeps every later change (validation, `init`, `virtual`) compatible. - Explain the `MissingFieldException` scenario: a shared library changes a field to a property, and the consumer that was not rebuilt breaks at run time, not at compile time. - Mention the source breaks too: `ref` and `out` arguments, and struct members mutated through the property.
- Is changing a public field to an auto-property also a source-breaking change?Mostly not: `booking.GuestName = "Ana"` reads the same and recompiles cleanly. Source breaks only where code relied on the field being a variable: passing it as a `ref` or `out` argument (CS0206), mutating a member of a struct-typed field through it (CS1612), or reflection that calls `GetField("GuestName")` and now gets null. The binary break is the bigger trap, because callers that are not recompiled fail at run time with `MissingFieldException`.
- Where does an auto-property's value actually live, and can you reach it?In a private field the compiler emits with the metadata name `<GuestName>k__BackingField`, which C# source cannot name, so only the accessors use it. You can put an attribute on it with `[field: ...]` on the property, reflection with `BindingFlags.NonPublic | BindingFlags.Instance` lists it, and since C# 14 an accessor body can read and write it through the `field` keyword.
- A property is just a field with nicer syntax; callers touch the same storage.
- A public field can become a property later without recompiling any consumer.
- A property can be passed as a ref argument exactly like a field.
- Public fields are fine whenever there is no validation to write yet.
- Fields can be virtual or abstract, so properties add no polymorphism.