SHARE:

Introducing C# 9: Init only properties

Introduction

.NET 5 brings a new version of the C# language: C# 9.

In this article we will discuss on a new feature: Init only properties

Init only properties without readonly properties

C# 9 Introduces init accessor (variant of set accessor) that allows properties to be assigned once during object initialization.

Example of a simple class Product without private member:

Object inialization:

Because init accessor, the property CategoryId becomes immutable, but can be assigned during object initialization only, which makes any subsequent assignment illegal.

Init only properties with readonly properties

init accessors can only be called during initialization, they makes mutable readonly fields only during object initialization:

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: