Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 182 ยท Classes and Objects

Properties

Master C# properties - get and set accessors, auto-properties, init-only and required members, computed properties, validation in setters, backing fields and the C# 14 field keyword.

In the previous lesson we kept data in public fields. That works, but it is a trap: any code anywhere can put any value into a public field, and you can never add a rule later without changing every caller. Properties are C#'s answer. A property looks like a field to the code that uses it (person.Age = 30), but behind the scenes it runs code, so the class stays in control.

Properties are used everywhere in .NET: string.Length, List<T>.Count, DateTime.Now. By the end of this lesson you will be able to write them in every form modern C# offers, including init, required, and the field keyword added in C# 14.

From a field to a property

Here is the long, explicit form: a private backing field plus a property with a get accessor that returns it and a set accessor that assigns it.

C# A property with a backing field

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Inside set, the special word value holds whatever was assigned. Callers cannot tell the difference between this and a field, but now there is a place to add logic. Because that logic can be added later without changing callers, public data in C# is almost always a property, never a field.

Auto-properties

When the accessors do nothing special, you do not need to write the backing field. An auto-property makes the compiler create a hidden one:

C#
public string Name { get; set; } = "";

Everything in the previous example collapses to that single line. You can also give the property an initial value (= "") as shown.

C# Auto-properties and read-only auto-properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A property with only get is read-only: it can be assigned in an initializer or in the constructor, then never again. That is the simplest way to build objects that cannot be changed by accident.

Access modifiers on accessors

Each accessor may have its own visibility, as long as it is more restrictive than the property itself. The common pattern is a public getter with a private setter: everyone can read the value, only the class can change it.

C# A private setter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Outside the class, t.Target = 99; would not compile. All changes go through methods that can check the rules.

init-only properties and required members

Read-only properties force you to pass everything through a constructor. Sometimes you want the readable object initializer syntax, but you also want the object to be unchangeable afterwards. That is what init (C# 9) is for: the property can be set while the object is being created, in a constructor or object initializer, and never after.

The required modifier (C# 11) goes further: the compiler refuses to compile code that creates the object without setting that member.

C# init and required

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

If you forget a required member, the error appears at compile time, not in production:

C# Missing a required member (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The compiler reports error CS9035: Required member 'Employee.Department' must be set in the object initializer or attribute constructor. Using required plus init is the modern way to model plain data objects: readable creation, no forgotten fields and no later mutation.

Computed properties

A property does not need to store anything. It can calculate its value each time it is read. Use the expression-bodied form => for these.

C# Computed properties

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because Area has no storage, it can never go out of date. If you stored it in a field, you would have to update it whenever Width or Height changed. The guideline: a property should be cheap and free of surprises. If reading it does heavy work, hits a database or can fail, make it a method instead (LoadOrders(), not Orders).

Validation in setters

The classic reason for a full property is to check values as they arrive. Throw an exception to refuse bad data.

C# Validating in a setter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The is < 0 or > 100 is a pattern. The message printed includes the offending value and parameter name, which ArgumentOutOfRangeException appends to the text. Run the example to see exactly what it prints.

The field keyword (C# 14)

The example above forced us to declare _grade by hand just to run a check in the setter. Before C# 14, the moment you needed any logic in one accessor you lost the auto-property and had to write the backing field and both accessors. C# 14 (shipped with .NET 10) adds the contextual keyword field, which refers to the compiler-generated backing field inside an accessor.

C# The field keyword

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

You write logic only in the accessor that needs it; the other stays automatic. field is not a normal variable: it exists only inside accessors of a property that uses it.

If your class already has a member or variable called field, the new keyword can change the meaning of your code. Write @field to refer to your own identifier, or this.field for a member. The compiler warns when it sees the ambiguity.

Properties versus fields versus methods

Question Choose
Part of the public surface of a type? Property, never a public field
Pure data with no rules? Auto-property
Value can be derived from other data? Computed property (=>)
Expensive, can fail, or has side effects? Method
Must be set when creating the object? required + init
Must never change after creation? { get; } or { get; init; }

One more point for performance fans: the JIT compiler inlines trivial property accessors, so an auto-property is as fast as a field in practice. There is no speed reason to avoid them.

Common mistakes

  • Recursion in the setter. Writing set { Name = value; } calls the setter again forever and ends in a stack overflow. Assign to the backing field (or field).
  • Heavy work in a getter. Debuggers and serializers read properties freely. Surprising side effects there cause confusing bugs.
  • Returning a mutable collection. A getter returning your private List<T> lets callers change it. Return IReadOnlyList<T> instead.
  • Forgetting that init allows setting in the initializer only. It is not a way to mutate later.
  • Using required and forgetting it affects every creation site. That is the point, but it is a breaking change when added to an existing type.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does public string Name { get; } declare?

    With only a get accessor the property is read-only; the compiler still allows assignment in the constructor or initializer.
  2. 2. Which keyword makes the compiler reject object creation if a member is not set?

    required (C# 11) forces the member to be set in the object initializer or constructor. init only restricts when it may be assigned.
  3. 3. What is wrong with public int Age { get { return Age; } }?

    The property returns itself instead of a backing field, which recurses infinitely. Use a private field or the field keyword.
  4. 4. In C# 14, what does the contextual keyword field refer to?

    Inside an accessor, field is the hidden backing field; value is the assigned value.
  5. 5. When should something be a method instead of a property?

    Callers expect property reads to be fast and safe. Costly or failing operations are clearer as methods.

Summary

  • A property looks like a field but runs accessor code, so the class stays in control of its data.
  • Use auto-properties ({ get; set; }) when no logic is needed; omit set for read-only, use private set to restrict writes.
  • init allows assignment only during creation; required forces callers to supply a value.
  • Computed properties (=>) derive their value and never go stale.
  • Validate in setters by throwing exceptions; in C# 14 the field keyword avoids writing the backing field by hand.
  • Keep properties cheap and predictable; use methods for work.

Next: Constructors and Object Initialization