skip to content

Fields and Properties

Fields hold state, properties wrap it with get, set and init, and the C# 14 field keyword reaches the backing field. Interviewers ask when a property beats a public field.

on this pageshow

explore

questions

5

In C#, why should a class expose GuestName as a property rather than a public field, even when the property only stores a value?

level: juniorimportance: must knowfreq 75%

answer

  1. accessor methods, not storage
  2. get_GuestName and set_GuestName
  3. validation later, callers untouched
  4. compiled callers and MissingFieldException
  5. ref arguments need a variable

basics

~20 s

A 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 s

An 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 lines
csharp
var 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

for a junior

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.

for a middle

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.

for a senior

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.

for a principal

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.
open as a page

In C#, how do you declare an indexer so booking[night] reads and writes a nightly rate, and how does it differ from a property?

level: juniorimportance: should knowfreq 40%

basics

~10 s

Declare it with this and a parameter list: public decimal this[DateOnly night] { get ...; set ...; }. It is a property whose accessors take parameters: instance-only, overloadable by parameter types and never auto-implemented.

open as a page

In C# 14, how does the field keyword let a Nights property validate its setter without a declared backing field, and what skips that validation?

level: middleimportance: should knowfreq 25%

basics

~20 s

In C# 14, field names the compiler-synthesized backing field inside a property accessor, so get; stays automatic while set validates and assigns field. A property initializer skips the setter and writes the backing field directly.

open as a page

In C#, when can a HotelBooking's GuestName be assigned if it has an init accessor, a private set accessor, or is a readonly field?

level: middleimportance: should knowfreq 60%

basics

~20 s

An init accessor is assignable only during creation: an object initializer, a constructor or another init accessor. A private setter works any time, but only inside the class. A readonly field takes its initializer, a constructor or an init accessor.

open as a page

In C#, why does new HotelBooking("Ana Ruiz") still fail with CS9035 when that constructor assigns the required GuestName, and what does [SetsRequiredMembers] change?

level: seniorimportance: should knowfreq 40%

basics

~20 s

The required check runs at each creation site and never looks inside constructor bodies, so callers must still set every required member. [SetsRequiredMembers] declares that the constructor sets them all and switches the check off, without verifying it.

open as a page