Skip to content

Fields

Context: Fields are variables declared directly inside a class. They hold the state of an object.

[access modifier] type fieldName;
public class Order
{
private int _id;
public string CustomerName;
protected double _totalAmount;
}

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 can only be set in the constructor or at declaration.

public class Config
{
public readonly string AppName = "MyApp";
}

Use the dot operator.

Order order = new Order();
order.CustomerName = "Acme Inc.";