0Pricing
C# Academy · Lesson

The required Modifier

Force callers to set essential properties.

The required Modifier

The required modifier forces callers to set a property (or field) when creating an object. It moves "you forgot a value" errors from runtime to compile time.

using System;

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

var p = new Person { Name = "Ada" };
Console.WriteLine(p.Name); // Ada

Omitting a required Member Fails to Compile

If a caller leaves out a required member, the compiler reports an error before the program ever runs.

using System;

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

// var bad = new Person { }; // compile error: Name is required
var good = new Person { Name = "Lin" };
Console.WriteLine(good.Name); // Lin

All lessons in this course

  1. init-Only Setters
  2. The required Modifier
  3. Immutable Object Patterns
  4. with Expressions on Records
← Back to C# Academy