init-only setters and required members

suggest change

Before C# 9 you had two ways to give a class its data, and each had a drawback:

// option 1: mutable, anyone can change it later
var a = new MutablePoint { X = 1, Y = 2 };
a.X = 100;

// option 2: immutable, but only through the constructor
var b = new FixedPoint(1, 2);
Console.WriteLine($"{a.X} {b.X}");

class MutablePoint
{
    public int X { get; set; }
    public int Y { get; set; }
}

class FixedPoint(int x, int y)
{
    public int X { get; } = x;
    public int Y { get; } = y;
}
100 1

Object initializers (new T { A = 1, B = 2 }) are readable, let callers skip optional values, and don't break when you add a property. They only worked with set, though, so the object stayed mutable forever. Get-only properties are immutable, but you need a constructor with one parameter per property, and the call sites turn into new Thing("a", "b", null, 3, true).

Two features fix this:

Together they give you immutable objects built with object-initializer syntax, where forgetting a property is a compile error.

The examples are .NET 10 / C# 14 file-based programs: save the code as app.cs and run it with dotnet run app.cs. All output comes from real runs.

init accessors

Replace set with init:

var p = new Point { X = 3, Y = 4 };
Console.WriteLine($"{p.X}, {p.Y}");

var q = new Point(1, 2);
Console.WriteLine($"{q.X}, {q.Y}");

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

    public Point() { }

    public Point(int x, int y)
    {
        X = x;   // allowed: inside a constructor
        Y = y;
    }
}
3, 4
1, 2

An init property can be assigned:

Anywhere else is a compile error, including the type's own methods:

var p = new Point { X = 3, Y = 4 };
p.X = 10;

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

    public void Move(int dx) => X += dx;
}
a2.cs(2,1): error CS8852: Init-only property or indexer 'Point.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.
a2.cs(9,33): error CS8852: Init-only property or indexer 'Point.X' can only be assigned in an object initializer, or on 'this' or 'base' in an instance constructor or an 'init' accessor.

You can still give init properties default values with an auto-property initializer ({ get; init; } = 30;). The object initializer runs after the constructor and the property initializers, so a value set by the caller wins.

Validation and readonly fields

An init accessor can have a body, like set. It runs while the object is being initialized, so it can assign readonly fields, which a set accessor can't:

var t = new Temperature { Celsius = 21.5 };
Console.WriteLine(t);

try
{
    var bad = new Temperature { Celsius = -300 };
}
catch (ArgumentOutOfRangeException ex)
{
    Console.WriteLine(ex.Message);
}

class Temperature
{
    private readonly double celsius;

    public double Celsius
    {
        get => celsius;
        init
        {
            ArgumentOutOfRangeException.ThrowIfLessThan(value, -273.15);
            celsius = value;   // readonly field: allowed in init
        }
    }

    public double Fahrenheit => celsius * 9 / 5 + 32;

    public override string ToString() => $"{Celsius} C = {Fahrenheit} F";
}
21.5 C = 70.7 F
value ('-300') must be greater than or equal to '-273.15'. (Parameter 'value')
Actual value was -300.

In C# 14 the field keyword gives you the compiler-generated backing field, so a normalizing init fits on one line:

var u = new User { Name = "  ada  ", Email = "Ada@Example.com" };
Console.WriteLine($"[{u.Name}] [{u.Email}]");

class User
{
    public string Name { get; init => field = value.Trim(); } = "";
    public string Email { get; init => field = value.ToLowerInvariant(); } = "";
}
[ada] [ada@example.com]

Note that the = "" initializer doesn't go through the init accessor. It assigns the backing field directly.

init is shallow

init protects the property, not the object it points to. A List<T> behind an init property can still be changed:

var order = new Order { Id = 1, Lines = ["apple", "pear"] };
order.Lines.Add("plum");            // compiles: the list itself is mutable
Console.WriteLine(string.Join(", ", order.Lines));

var safe = new SafeOrder { Id = 2, Lines = ["apple", "pear"] };
// safe.Lines.Add("plum");          // error: IReadOnlyList has no Add
Console.WriteLine(string.Join(", ", safe.Lines));

class Order
{
    public int Id { get; init; }
    public List<string> Lines { get; init; } = [];
}

class SafeOrder
{
    public int Id { get; init; }
    public IReadOnlyList<string> Lines { get; init; } = [];
}
apple, pear, plum
apple, pear

For real immutability use IReadOnlyList<T>, ImmutableArray<T> or other immutable types for the property values. See Immutability for more.

init on structs and with expressions

init works on structs too, including readonly struct, where set isn't allowed. Since C# 10, with works on any struct and on anonymous types, and it uses the init accessors to set the changed properties on the copy:

var a = new Size { Width = 10, Height = 20 };
var b = a with { Height = 30 };     // works for structs (C# 10)
Console.WriteLine($"{a.Width}x{a.Height} {b.Width}x{b.Height}");

var anon = new { Name = "Ada", Year = 1815 };
Console.WriteLine(anon with { Year = 1816 });

readonly struct Size
{
    public int Width { get; init; }
    public int Height { get; init; }
}
10x20 10x30
{ Name = Ada, Year = 1816 }

On a plain class, with isn't available, because the compiler doesn't know how to copy it:

k1.cs(2,9): error CS8858: The receiver type 'Point' is not a valid record type and is not a struct type.

Use a record if you want with on a reference type (see Records).

init is a compile-time rule

At runtime an init accessor is an ordinary setter. The compiler marks it with the IsExternalInit modifier so that other C# code can't call it, but reflection (and serializers) can:

var p = new Point { X = 1 };
typeof(Point).GetProperty("X")!.SetValue(p, 42);
Console.WriteLine(p.X);

var setter = typeof(Point).GetProperty("X")!.SetMethod!;
Console.WriteLine(string.Join(", ", setter.ReturnParameter.GetRequiredCustomModifiers().Select(t => t.FullName)));

class Point
{
    public int X { get; init; }
}
42
System.Runtime.CompilerServices.IsExternalInit

This is what lets System.Text.Json, EF Core and configuration binding fill init properties without any extra work.

required members

init stops callers from changing a property later, but nothing makes them set it in the first place. new Customer() compiles and leaves Name empty. Mark the property required and the compiler checks every object creation:

var ok = new Customer { Name = "Ada", Email = "ada@example.com" };
Console.WriteLine($"{ok.Name} <{ok.Email}> {ok.Phone ?? "(no phone)"}");

var bad = new Customer { Name = "Grace" };

class Customer
{
    public required string Name { get; init; }
    public required string Email { get; init; }
    public string? Phone { get; init; }
}
d1.cs(4,15): error CS9035: Required member 'Customer.Email' must be set in the object initializer or attribute constructor.

It's an error, not a warning, and you get one per missing member. Without the bad line the program prints:

Ada <ada@example.com> (no phone)

required also works with set properties and with fields. It only means "must be assigned when the object is created"; it says nothing about mutability:

var c = new Counter { Count = 5 };
c.Count++;
Console.WriteLine(c.Count);

class Counter
{
    public required int Count;   // a required field, still mutable
}
6

required and nullable reference types

required fixes the CS8618 warning ("Non-nullable property must contain a non-null value when exiting constructor") because the compiler now knows the caller provides the value. The two features check different things, though: required checks that the property is assigned, the nullable annotations check whether null is an acceptable value. Assigning a possibly-null value to a required string gives the usual nullable warning:

string? maybe = null;
var n = new Customer { Name = maybe, Email = "x" };

class Customer
{
    public required string Name { get; init; }
    public required string Email { get; init; }
}
d2.cs(2,31): warning CS8601: Possible null reference assignment.

A required string? property is legal too: the caller must say something, and null is an allowed answer. The nullable reference types article covers this in more detail.

Rules

The compiler enforces a few rules about where required can go:

public class Config
{
    internal required string Secret { get; init; }
    public required string Name { get; }
    public static required int Count { get; set; }
}
interface IThing { required string Id { get; set; } }
g1.cs(3,30): error CS9032: Required member 'Config.Secret' cannot be less visible or have a setter less visible than the containing type 'Config'.
g1.cs(4,28): error CS9034: Required member 'Config.Name' must be settable.
g1.cs(5,32): error CS0106: The modifier 'required' is not valid for this item
g1.cs(7,36): error CS0106: The modifier 'required' is not valid for this item

A derived class inherits the requirements of its base class and can add its own:

var e = new Employee { Name = "Ada", Email = "ada@example.com", Department = "R&D" };
Console.WriteLine($"{e.Name} {e.Department}");

var bad = new Employee { Department = "R&D" };

class Person
{
    public required string Name { get; init; }
    public required string Email { get; init; }
}

class Employee : Person
{
    public required string Department { get; init; }
}
f1.cs(4,15): error CS9035: Required member 'Person.Email' must be set in the object initializer or attribute constructor.
f1.cs(4,15): error CS9035: Required member 'Person.Name' must be set in the object initializer or attribute constructor.

A derived class can't drop a requirement. Overriding a virtual required property without required fails with error CS9030: 'Derived.Id' must be required because it overrides required member 'Base.Id'.

Types with required members also can't satisfy the new() generic constraint, because new T() has no object initializer to set them:

var x = Create<Settings>();
static T Create<T>() where T : new() => new T();

class Settings
{
    public required string Path { get; init; }
}
g2.cs(1,9): error CS9040: 'Settings' cannot satisfy the 'new()' constraint on parameter 'T' in the generic type or or method 'Create<T>()' because 'Settings' has required members.

(The doubled "or" is in the real compiler message.)

Constructors and [SetsRequiredMembers]

The compiler doesn't look inside constructors to see what they assign. A constructor that sets every required property still doesn't count:

var c = new Customer("Ada", "ada@example.com");

class Customer
{
    public required string Name { get; init; }
    public required string Email { get; init; }

    public Customer() { }

    public Customer(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
e1.cs(1,13): error CS9035: Required member 'Customer.Email' must be set in the object initializer or attribute constructor.
e1.cs(1,13): error CS9035: Required member 'Customer.Name' must be set in the object initializer or attribute constructor.

Put [SetsRequiredMembers] (from System.Diagnostics.CodeAnalysis) on a constructor to tell the compiler "this constructor sets all required members, don't check callers":

using System.Diagnostics.CodeAnalysis;

var a = new Customer("Ada", "ada@example.com");              // no initializer needed
var b = new Customer { Name = "Grace", Email = "grace@example.com" };
var c = new Customer("Linus", "linus@example.com") { Email = "torvalds@example.com" };
Console.WriteLine($"{a.Name} {b.Name} {c.Email}");

class Customer
{
    public required string Name { get; init; }
    public required string Email { get; init; }

    public Customer() { }

    [SetsRequiredMembers]
    public Customer(string name, string email)
    {
        Name = name;
        Email = email;
    }
}
Ada Grace torvalds@example.com

Callers can still use an object initializer after such a constructor to override values, as c does.

The attribute is a promise, and the compiler trusts it. It turns off checking for all required members, including ones you add later:

using System.Diagnostics.CodeAnalysis;

var c = new Customer("Ada");
Console.WriteLine($"Level = {c.Level}");
Console.WriteLine(c.Email.Length);

class Customer
{
    public required string Name { get; init; }
    public required string Email { get; init; }
    public required int Level { get; init; }

    [SetsRequiredMembers]
    public Customer(string name)
    {
        Name = name;   // forgot Email and Level
    }
}
e3.cs(14,12): warning CS8618: Non-nullable property 'Email' must contain a non-null value when exiting constructor. Consider adding the 'required' modifier or declaring the property as nullable.
Level = 0
Unhandled exception. System.NullReferenceException: Object reference not set to an instance of an object.

Nullable analysis catches the missing Email, because with the attribute the constructor is again responsible for non-nullable properties. Nothing catches Level: value types silently get their default. Use [SetsRequiredMembers] only on constructors that really set everything, and revisit them when you add a required member.

Constructor chaining

A constructor that chains to a [SetsRequiredMembers] constructor with : base(...) or : this(...) must have the attribute too. Otherwise the derived class's own required members could slip through:

using System.Diagnostics.CodeAnalysis;

class Person
{
    public required string Name { get; init; }

    [SetsRequiredMembers]
    public Person(string name) => Name = name;
}

class Employee : Person
{
    public required string Department { get; init; }

    public Employee(string name) : base(name) { }
}
f3.cs(15,36): error CS9039: This constructor must add 'SetsRequiredMembers' because it chains to a constructor that has that attribute.

The fix is to set the derived members as well and add the attribute:

using System.Diagnostics.CodeAnalysis;

var e = new Employee("Ada", "R&D");
Console.WriteLine($"{e.Name} {e.Department}");

class Person
{
    public required string Name { get; init; }

    public Person() { }

    [SetsRequiredMembers]
    public Person(string name) => Name = name;
}

class Employee : Person
{
    public required string Department { get; init; }

    public Employee() { }

    [SetsRequiredMembers]
    public Employee(string name, string department) : base(name)
    {
        Department = department;
    }
}
Ada R&D

A good rule: if a type needs a constructor with parameters for every value, you probably don't need required at all. Use get-only or init properties set by that constructor. Use required when object initializers are the main way to create the type.

With records

Positional record parameters are already mandatory, since they're constructor arguments, and they generate init properties. required is useful for the extra properties in the record body:

var req = new HttpRequestInfo("GET", "/users") { Host = "api.example.com" };
Console.WriteLine(req);

var copy = req with { Path = "/orders" };   // no need to repeat Host
Console.WriteLine(copy);

record HttpRequestInfo(string Method, string Path)
{
    public required string Host { get; init; }
    public int TimeoutSeconds { get; init; } = 30;
}
HttpRequestInfo { Method = GET, Path = /users, Host = api.example.com, TimeoutSeconds = 30 }
HttpRequestInfo { Method = GET, Path = /orders, Host = api.example.com, TimeoutSeconds = 30 }

A with expression copies an object that already has all its required members, so you don't have to set them again.

Nominal records (all properties in the body) work the same way, and so do record structs:

var a = new Money { Amount = 9.99m, Currency = "EUR" };
var b = a with { Amount = 19.99m };
Console.WriteLine($"{a} {b}");

readonly record struct Money
{
    public required decimal Amount { get; init; }
    public required string Currency { get; init; }
}
Money { Amount = 9.99, Currency = EUR } Money { Amount = 19.99, Currency = EUR }

For structs, required only applies to new Money { ... } and new Money(). default and array elements bypass it, as they bypass every struct constructor. With the same Money struct:

var m = default(Money);
var n = new Money[2];
Console.WriteLine(m.Currency is null);
Console.WriteLine(n[0]);
True
Money { Amount = 0, Currency =  }

With System.Text.Json

System.Text.Json sets init properties (since .NET 5) and honors the required keyword (since .NET 7): if a required property is missing from the JSON, deserialization throws. For properties you don't want to mark required in C#, [JsonRequired] has the same effect for JSON only:

using System.Text.Json;
using System.Text.Json.Serialization;

Parse("""{"name":"Ada","email":"ada@example.com","age":36}""");
Parse("""{"name":"Ada","age":36}""");
Parse("""{"name":"Ada","email":"ada@example.com"}""");
Parse("""{"name":null,"email":"ada@example.com","age":36}""");

void Parse(string json)
{
    try
    {
        var u = JsonSerializer.Deserialize(json, AppJson.Default.User)!;
        Console.WriteLine($"ok: {u.Name ?? "<null>"} {u.Email} {u.Age}");
    }
    catch (JsonException ex)
    {
        Console.WriteLine($"error: {ex.Message}");
    }
}

class User
{
    public required string Name { get; init; }
    public required string Email { get; init; }

    [JsonRequired]
    public int Age { get; init; }
}

[JsonSourceGenerationOptions(JsonSerializerDefaults.Web)]
[JsonSerializable(typeof(User))]
partial class AppJson : JsonSerializerContext;
ok: Ada ada@example.com 36
error: JSON deserialization for type 'User' was missing required properties including: 'email'.
error: JSON deserialization for type 'User' was missing required properties including: 'age'.
ok: <null> ada@example.com 36

The last line shows the gap: "name": null counts as present, so a required string ends up null. To reject that too, turn on RespectNullableAnnotations (.NET 9+):

[JsonSourceGenerationOptions(JsonSerializerDefaults.Web, RespectNullableAnnotations = true)]
ok: Ada ada@example.com 36
error: JSON deserialization for type 'User' was missing required properties including: 'email'.
error: JSON deserialization for type 'User' was missing required properties including: 'age'.
error: The constructor parameter 'Name' on type 'User' doesn't allow null values. Consider updating its nullability annotation. Path: $.name | LineNumber: 0 | BytePositionInLine: 12.

With both, a required string Name { get; init; } property in a DTO really guarantees a non-null value after deserialization.

The example uses a source-generated JsonSerializerContext because file-based apps have Native AOT enabled by default, which turns off reflection-based JSON serialization. With JsonSerializer.Deserialize<User>(json, options) in a normal project the behavior is the same.

Older target frameworks

Both features are compiler features that rely on a few types the compiler looks up by name. .NET 5+ has IsExternalInit, and .NET 7+ has the attributes for required. If you target netstandard2.0 or .NET Framework with a modern LangVersion, you get errors like these:

Lib.cs(1,14): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.CompilerFeatureRequiredAttribute..ctor'
Lib.cs(1,14): error CS0656: Missing compiler required member 'System.Runtime.CompilerServices.RequiredMemberAttribute..ctor'
Lib.cs(3,40): error CS0518: Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported

You can declare the types yourself as internal in your project and the compiler will use them:

namespace System.Runtime.CompilerServices
{
    internal static class IsExternalInit { }

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, Inherited = false)]
    internal sealed class RequiredMemberAttribute : Attribute { }

    [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)]
    internal sealed class CompilerFeatureRequiredAttribute(string featureName) : Attribute
    {
        public string FeatureName { get; } = featureName;
        public bool IsOptional { get; init; }
    }
}

namespace System.Diagnostics.CodeAnalysis
{
    [AttributeUsage(AttributeTargets.Constructor, Inherited = false)]
    internal sealed class SetsRequiredMembersAttribute : Attribute { }
}

With this file added, the netstandard2.0 library builds. Packages such as PolySharp generate these polyfills for you.

When to use what

You want Use
Value fixed after creation, set through an object initializer { get; init; }
Value fixed after creation, always given to a constructor { get; } set in the constructor (or a positional record)
Callers must provide the value, object initializer syntax required ... { get; init; }
Optional value with a default { get; init; } = defaultValue; (see Initializing Properties)
A convenience constructor on a type with required members the constructor sets them all and has [SetsRequiredMembers]
Value can change later { get; set; }, with required if it must be set at creation

Takeaways:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents