Hello Everyone,

Back again after a long back with the new article where we are going to learn about records that are released with C# 9.0.

System Requirement

Please install Microsoft .NET SDK 5.0 + to run these exercises.

Before going into records let’s just look for object initialization process with class and properties,

class Program

The one big limitation is that properties have to be mutable for object initialization to work.

If you want the whole object as immutable and behave like a value then you should declare it as a record. A record is still a class but the record keyword adds several value-like behaviors.

In nutshell, Records is a compact and easy way to define a reference type that automatically gets value-based equality and being immutable.

Let us just see how we can declare the records in c#,

class Program

Value-Based equality check

If you think of class object comparison check it’s going to happen on the reference it is pointing to so if you want to check that two class objects are equal or not having the same content you need to write extra logic to perform a value-based equality check but in case of records you are getting this feature inbuilt let’s see an example of it below,

Value-Based Equality Check

Immutability

Once you created an instance of records with some values you can not change it later because every instance is immutable in the case of records. For any change, you can create a new instance of records but in the case of a class object, you are allowed to change the value of a particular instance.

Immutability Check

With-Expression

When working with immutable data, a common pattern is to create new values from existing ones to represent a new state. For instance, if our employee wants to change their EmployeeId by keeping the same EmployeeName we will represent it as a new object which is a copy of the old one. This technique is often referred to as a non-destructive mutation.

With Expression Check

The with-expression works like actually copying the full state of the old object into a new object, then mutating that new object values according to the object initializer.

Inheritance

Records also support inheritance where the new record can be inherited from any base record by having any additional expression or capabilities lets take an example where we want to extend our Employee record and create a new Developer record having an additional expression of Skill.

Inheritance

Reference -

Thank You, See you in the next article !!

You can reach out or connect to me over here,

LinkedIn: https://www.linkedin.com/in/vaibhav-bhapkar

Email: vaibhavbhapkar.medium@gmail.com

If you want some technical topics to be discussed with group of participants please raise a request on following link: http://myblogsenquiry.somee.com/

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *