Skip to main content
Redhat Developers  Logo
  • Products

    Featured

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat OpenShift AI
      Red Hat OpenShift AI
    • Red Hat Enterprise Linux AI
      Linux icon inside of a brain
    • Image mode for Red Hat Enterprise Linux
      RHEL image mode
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • Red Hat Developer Hub
      Developer Hub
    • View All Red Hat Products
    • Linux

      • Red Hat Enterprise Linux
      • Image mode for Red Hat Enterprise Linux
      • Red Hat Universal Base Images (UBI)
    • Java runtimes & frameworks

      • JBoss Enterprise Application Platform
      • Red Hat build of OpenJDK
    • Kubernetes

      • Red Hat OpenShift
      • Microsoft Azure Red Hat OpenShift
      • Red Hat OpenShift Virtualization
      • Red Hat OpenShift Lightspeed
    • Integration & App Connectivity

      • Red Hat Build of Apache Camel
      • Red Hat Service Interconnect
      • Red Hat Connectivity Link
    • AI/ML

      • Red Hat OpenShift AI
      • Red Hat Enterprise Linux AI
    • Automation

      • Red Hat Ansible Automation Platform
      • Red Hat Ansible Lightspeed
    • Developer tools

      • Red Hat Trusted Software Supply Chain
      • Podman Desktop
      • Red Hat OpenShift Dev Spaces
    • Developer Sandbox

      Developer Sandbox
      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Secure Development & Architectures

      • Security
      • Secure coding
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
      • View All Technologies
    • Start exploring in the Developer Sandbox for free

      sandbox graphic
      Try Red Hat's products and technologies without setup or configuration.
    • Try at no cost
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • Java
      Java icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • API Catalog
    • Product Documentation
    • Legacy Documentation
    • Red Hat Learning

      Learning image
      Boost your technical skills to expert-level with the help of interactive lessons offered by various Red Hat Learning programs.
    • Explore Red Hat Learning
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

C# 9 init accessors and records

April 20, 2021
Tom Deseyn
Related topics:
.NETKubernetes
Related products:
Red Hat Enterprise Linux

Share:

    This is the fourth article in our C# 9 series. The previous articles covered top-level programs and target-typed expressions, new features for pattern matching, and new features for methods and functions.

    In this article, we’ll take a look at init accessors and records.

    Init accessors

    C# 9 introduces a new accessor for properties named init. The init accessor works like a public set accessor, but it can only be used during object initialization. Trying to set the property elsewhere gives a compilation error:

    public class Person
    {
     public string FirstName { get; init; }
     public string LastName { get; init; }
    }
     
    Person person = new()
    {
      FirstName = "John"       // OK.
    };
    
    person.FirstName = "Jane"; // error CS8852.
    

    init accessors can be used in the constructor. And, a body may be provided for the accessor, which can change readonly fields:

    public class Person
    {
     private readonly string _firstName;
     public Person(string firstName)
     {
       FirstName = firstName;
     }
     public string FirstName
     {
       get => _firstName;
       init =>
     	_firstName = value ?? throw new ArgumentNullException(nameof(value));
     }
     public string LastName { get; init; }
    }
    

    The init accessors (that are used in the object initializer) will be called after the constructor. This means we can validate the property value, but we can't validate the object as a whole because we don't know when the user has finished setting properties. If such validation is needed, init accessors cannot be used and values need to be passed as constructor arguments. Or, alternatively, an API accepting these types must validate them.

    Records

    C# classes are reference types. This means variables are not instances of the type, but they are references to an instance of that type (which lives on the managed heap). The default implementation of equality for reference types is to check whether two variables refer to the same instance:

    class Person { public string FirstName { get; set; }};
     
    Assert.False(new Person { FirstName = "John" }
             .Equals(new Person { FirstName = "John" }));
    

    When working with objects that represent data, it can be useful to be able to compare two different instances and see if they have the same values. That is exactly what the new C# 9 records enable:

    record Person { public string FirstName { get; set; }};
     
    Assert.True(new Person { FirstName = "John" }
             .Equals(new Person { FirstName = "John" }));
    

    We’ve changed the Person declaration from class to record. Now two different instances that have the same values are considered equal.

    The Person record is a class for which the compiler generated an IEquatable and GetHashCode implementation that is based on the fields of the type. Doing this yourself in a class is possible, but it is tedious and error-prone.

    The compiler will also generate a ToString method that returns a string with the type name, public field values and readable property values.

    You can add constructors and other members to the record as you would for a regular class. Records support inheritance using the usual : syntax:

    record Student : Person
    {
     public int ID { get; set; }
    }
    

    The equality implementation takes into account the runtime type: A Person instance will never equal a Student instance.

    C# records can be used with init accessors, which provides a convenient way to build types that cannot be modified after their creation (immutable types):

    public record Person
    {
     public string? FirstName { get; init; }
     public string? LastName { get; init; }
    }
    

    When working with immutable data, new values are often created by modifying existing ones. Records support this via the with expression:

    Person jane = person with
    {
     FirstName = "Jane"
    };
    

    The with expression copies the values from an instance and allows changing it through the init accessors. The copying relies on a copy constructor that is generated for record types.

    A one-liner allows you to create an immutable record with a constructor and deconstruct method:

    record Person(string FirstName, string LastName);
     
    var person = new Person("John", "Doe");
    (string firstName, string lastName) = person;
    

    A body can be added to the record, to add additional members or refine the properties that would otherwise be auto-generated:

    record Person(string FirstName, string lastName)
    {
     public string LastName { get; } = lastName;
    }
    

    Conclusion

    In this article, we looked at init accessors, which we can use to declare immutable properties. We then saw how records make it easy to build reference types with value semantics. By combining init accessors and records, we can build immutable data models that support change via the with expression.

    Part 5 of the C# 9 series covers advanced features related to native interop and performance.

    C# 9 can be used with the .NET 5 SDK, which is available on Red Hat Enterprise Linux, Red Hat OpenShift, Fedora, Windows, macOS, and other Linux distributions.

    Last updated: June 17, 2021

    Recent Posts

    • Create and enrich ServiceNow ITSM tickets with Ansible Automation Platform

    • Expand Model-as-a-Service for secure enterprise AI

    • OpenShift LACP bonding performance expectations

    • Build container images in CI/CD with Tekton and Buildpacks

    • How to deploy OpenShift AI & Service Mesh 3 on one cluster

    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue