Introduction

C# 9 introduces Init-only properties that allow to make individual properties immutable. C# 9 introduces another great feature that enable a whole object to be immutable and make it acting like a value: Records. Let’s see in this article how Records work. Unlike the previous announcement from Microsoft (https://devblogs.microsoft.com/dotnet/welcome-to-c-9-0/), data class** (combined) keywords become now record keyword.

Data keyword

C# 9 Introduces a new keyword: **record **keyword. **record **keyword makes an object immutable and behave like a value type. data keyword replaces the init keyword for each property if you want the whole object (all properties) to be immutable.

Example:

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

The important thing to know here with Records is that members are implicitly public if you don’t precise it. Then the following class declaration is similar to the previous above:

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

Records introduce also public init-only auto-property (if you don’t to use explicitly private fields) which is a shorthand of the previous declaration (same meaning):

namespace CSharp9Demo.Models
	{
	    public record Product
	    {
	        string Name;
	        int CategoryId;
	    }
	}

With-expressions

We might want sometimes create new a object from another one because some property values are identical only one change, unfortunately your object is immutable. **with **keyword fixes that. It allows you create an object from another by specifying what property changes:

using System;
	using CSharp9Demo.Models

	namespace CSharp9Demo
	{
	    class Program
	    {
	        static void Main(string[] args)
	        {
	            var product = new Product
	            {
	                Name = "VideoGame",
	                CategoryId = 1
	            };

	            var newProduct = product with { CategoryId = 2 }

	            // newProduct.Name == "VideoGame"
	            // newProduct.CategoryId == 2
	        }
	    }
	}

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

Introducing C# 9: Records
82.05 GEEK