Fields
Context: Fields are variables declared directly inside a class. They hold the state of an object.
Declaration
Section titled “Declaration”[access modifier] type fieldName;Example
Section titled “Example”public class Order{ private int _id; public string CustomerName; protected double _totalAmount;}Field Initialization
Section titled “Field Initialization”Fields can be initialized at declaration or in the constructor.
public class Product{ private int _stock = 100; // initialized private readonly string _sku; // must be set in constructor public Product(string sku) => _sku = sku;}Readonly Fields
Section titled “Readonly Fields”readonly fields can only be set in the constructor or at declaration.
public class Config{ public readonly string AppName = "MyApp";}Accessing Fields
Section titled “Accessing Fields”Use the dot operator.
Order order = new Order();order.CustomerName = "Acme Inc.";