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:

namespace CSharp9Demo.Models
	{
	    public class Product
	    {
	        public string Name { get; set; }
	        public int CategoryId { get; init; }
	    }
	}

Object inialization:

using System;
	using CSharp9Demo.Models

	namespace CSharp9Demo
	{
	    class Program
	    {
	        static void Main(string[] args)
	        {
	            Console.WriteLine("Hello World!");
	            var product = new Product
	            {
	                Name = "VideoGame",
	                CategoryId = 1
	            };
	            product.CategoryId = 2; // illegal statement
	        }
	    }
	}

#.net 5 #csharp #csharp 9 #programming-c

Introducing C# 9: Init only properties
2.85 GEEK