Glossary / Fields

Fields

A field is a variable declared directly in a type or struct that stores state. Fields can be instance or static, mutable or readonly, and public or private; good design usually keeps fields private and exposes validated behavior through properties or methods.

Initialization and modifiers

Instance fields receive default values before constructors run, then field initializers execute as part of object construction. Static fields initialize as part of type initialization. readonly fields can be assigned at declaration or in constructors (instance/static respectively), but referenced objects can still mutate. const fields are compile-time constants whose values are substituted into consuming assemblies, so changing a public const can leave consumers with stale inlined values until recompiled.

C# 14 introduces field-backed properties and the contextual field keyword in supported property accessors, allowing accessor logic over compiler-generated backing storage. This is a versioned feature; distinguish it from declaring an ordinary field manually.

Encapsulation and performance

Exposing fields publicly makes validation, lazy computation, notifications, and binary evolution harder. Fields can be useful for implementation storage, constants, interop layouts, and performance-sensitive data structures. Struct fields and readonly semantics require attention to copying and defensive-copy behavior.

Interview questions

  1. Field vs property? Field is storage; property is accessor-based API.
  2. What does readonly mean? The field assignment is restricted after initialization/constructor; referenced contents may still mutate.
  3. Why avoid public const in libraries? Consumers may inline its value and retain stale constants after a library update.
  4. Do fields start uninitialized? They receive default values before constructors/initializers.
  5. What is C# 14 field? A contextual reference to a compiler-generated backing field in supported properties.

References