CodeBlanks Logo Icon CodeBlanks

init only setters

C# course · Intermediate · Lesson 27/116

Learn init-only properties writable only during initialization.

init only setters

The init keyword lets a property be assigned only during object construction; it cannot be changed afterwards. Declaration: public string Name { get; init; }.

This combines the flexibility of set with the safety of readonly. You assign with an object initializer: new Point { X = 3, Y = 4 }. But after creation, p.X = 5 is a compile error. This makes it easy to write immutable objects.

Why init?

Immutable objects are safer for concurrency: no other thread can change the value, so no locking is needed. init guarantees immutability after setup.

Also, the object initializer syntax works: new Point { X = 3, Y = 4 } lets you set values in one line. With a readonly field the initializer would not work; you would have to write a constructor. init removes that burden.

Exercise Add init properties to the Point class

Define a Point class. Add public int X { get; init; } and public int Y { get; init; } properties. Inside Main create an instance with new Point { X = 3, Y = 4 } and print X.

Show example solution
Add X and Y init properties to Point. In Main write Point p = new Point { X = 3, Y = 4 }; Console.WriteLine(p.X);
Example solution:
using System;

class Point
{
    public int X { get; init; }
    public int Y { get; init; }
}

class Program
{
    static void Main()
    {
        Point p = new Point { X = 3, Y = 4 };
        Console.WriteLine(p.X);
    }
}

Test yourself

  1. Which property can only be set at initialization?

    • public string Name { get; set; }
    • public string Name { get; init; }
    • public string Name { get; }
    • public string Name;
    Show answer

    public string Name { get; init; } — Correct. An init property can only be set at initialization.

  2. Complete the init property

    public string Name { get; ____; }
    Show answer
    public string Name { get; init; }
  3. Match each accessor to its behavior

    set
    Writable anytime
    init
    Only at initialization
    get
    Reading
    { get; }
    Read-only

All lessons in Intermediate