Properties and primary constructors

An auto-property

A property is a pair of accessors, get and set, that looks like a field from outside. The shortest form is the auto-property, public string Name { get; init; }, where the compiler supplies a hidden backing field that nothing else can reach. A property with only a getter is read-only, and one with only an init setter may be written while the object is being built.

var product = new Product { Name = "Pen", Price = 2.50m, Quantity = 3 }; Console.WriteLine(product); Console.WriteLine($"total {product.Total:F2}"); class Product { public required string Name { get; init; } public required decimal Price { get; init; } public int Quantity { get; init; } = 1; public decimal Total => Price * Quantity; public override string ToString() => $"{Name} x{Quantity}"; }

dotnet run

Pen x3
total 7.50

Total is computed on every read and stores nothing: it is a getter with an expression body, and no code can assign it. A computed property is the right shape for a value derived from the fields, as long as the calculation is cheap; an expensive one belongs in a method whose name says so.

init and required

init and required came in C# 9 and C# 11 and together they describe an immutable object with no constructor to write. init makes the setter callable only during construction, and required makes the compiler demand that the caller set the property:

A computed property and a setter

A property with a body can validate, clamp or convert what it stores. This class keeps its value in a private field and never lets it below absolute zero:

var temperature = new Temperature(); temperature.Celsius = 25; Console.WriteLine($"25 C is {temperature.Fahrenheit} F"); temperature.Celsius = -300; Console.WriteLine($"clamped to {temperature.Celsius} C"); class Temperature { private double celsius; public double Celsius { get => celsius; set => celsius = Math.Clamp(value, -273.15, 1000); } public double Fahrenheit => celsius * 9 / 5 + 32; }

dotnet run

25 C is 77 F
clamped to -273.15 C

The set accessor has one implicit parameter, value, and it decided what to keep. The object never held -300: the field and the getter both report the clamp, so every reader sees the same number. A setter that silently changes the value is a design choice; a setter that quietly drops it is a bug. The property on the next lesson, a primary constructor, takes the value once and has no setter at all.

A primary constructor

A primary constructor puts the parameters in the class header: class Order(string customer, int quantity, decimal price). The names are in scope in every method and initialiser of the class, and the compiler captures them in hidden fields only if they are used after the constructor returns. C# 12 allows it on a class as well as on a record.

var order = new Order("Anna", 3, 2.50m); Console.WriteLine(order.Describe()); Console.WriteLine($"total {order.Total:F2}"); class Order(string customer, int quantity, decimal price) { public string Customer => customer; public decimal Total => quantity * price; public string Describe() => $"{customer}: {quantity} at {price:F2}"; }

dotnet run

Anna: 3 at 2.50
total 7.50

The three parameters became three read-only properties of the same name in spirit, though the class exposes only the ones it declares. A primary constructor makes a small class short; it does not replace a record, which also brings value equality and with, and the two lessons on records come after the one on structs.

A required member that is not set

The compiler checks required at every call site. This program builds a product with a price and forgets the name:

var product = new Product { Price = 1m }; Console.WriteLine(product.Name); class Product { public required string Name { get; init; } public required decimal Price { get; init; } }

dotnet build

Program.cs(1,19): error CS9035: Required member 'Product.Name' must be set in the object initializer or attribute constructor.

Build FAILED.

Program.cs(1,19): error CS9035: Required member 'Product.Name' must be set in the object initializer or attribute constructor.
0 Warning(s)
1 Error(s)

Time Elapsed 00:00:03.81

The error names the property and the call site, which is the pair a reader needs. Without required the same program compiles with warning CS8618 and prints an empty line, because a string property defaults to null, neither the empty string nor an error; the lesson on nullable reference types explains why that is a warning and not a refusal.

Exercises

  1. Add a Discount property with an init setter and a default of zero, and use it in Total.
  2. Make the temperature setter throw for a value below absolute zero instead of clamping, and wrap the assignment in a try/catch when you get to exceptions.
  3. Give Order a fourth primary-constructor parameter and a Discount computed from it.
  4. Remove required from Name and print the property of an object built without it. What does the line show?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an auto-property public int N { get; init; } hide?

    Answer

    A private backing field the compiler generates

    The compiler writes a field and the two accessors around it, and the field has no name in C#.

  2. When may an init accessor be called?

    Answer

    During construction, including an object initializer

    init is writable while the object is being built and read-only afterwards.

  3. What does this program print? var p = new P { Name = "Pen" }; Console.WriteLine(p.Name); class P { public required string Name { get; init; } }

    Answer

    Pen

    The required property was set in the initializer, so the read returns the value given.

  4. What does a computed property like public decimal Total => Price * Quantity; do?

    Answer

    Runs the calculation on every read and stores nothing

    The expression body is the getter, so each read of Total runs the multiplication.

  5. What is the implicit parameter of a set accessor called?

    Answer

    value

    The setter receives the assigned value in a parameter named value.

  6. What does this program print? var t = new T(); t.N = 5; Console.WriteLine(t.N + t.Double); class T { public int N { get; set; } public int Double => N * 2; }

    Answer

    15

    N is 5 and Double reads it as 10, so the sum is 15.

  7. What does a primary constructor on a class give you?

    Answer

    Parameters in the class header, in scope in its members

    The parameters are captured into fields where needed; equality and with stay with records.

  8. Why does new Product { Price = 1m } fail when Name is required?

    Answer

    CS9035: a required member must be set where the object is created

    The compiler enforces required at every construction site, which is the point of the keyword.

  9. What is the value of a string property nobody set?

    Answer

    null

    Reference-type fields are zeroed to null, and nullable analysis warns when one is read unsafely.

  10. Which is the better reason to use a property rather than a public field?

    Answer

    A property can validate, compute or change its implementation later

    A property is a method pair behind field syntax, so the class keeps control of every read and write.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image