C# 9.0 - Record Type
Wriju's Blog
Posted on November 13, 2020
In C# often we use class to create a structure for data. They were generic reference type in C#. Now we have a specialized record
type for the same purpose.
public record Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public Employee(int _id, string _fullName)
{
(Id, FullName) = (_id, _fullName);
}
}
To use as normal
var emp = new Employee ( 1, "Wriju" );
Console.WriteLine("{0} - {1}", emp.Id, emp.FullName);
Compiler generates class
in intermediate code (IL). The main purpose of the record
type is to provide the semantics for equality.
You can also use Deconstruct
method to retrieve the values,
public record Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public Employee(int _id, string _fullName)
{
(Id, FullName) = (_id, _fullName);
}
internal void Deconstruct(out int _id, out string _fullName) =>
(_id, _fullName) = (this.Id, this.FullName);
}
To call use the normal out
parameter assignment
var emp = new Employee ( 1, "Wriju" );
int _id;
string _fullName;
(_id, _fullName) = emp;
Console.WriteLine("{0} - {1}", _id, _fullName);
You can also create a copy of the record
with changed property value using with
keyword.
var emp2 = emp with { FullName = "Wriju Ghosh" };
💖 💪 🙅 🚩
Wriju's Blog
Posted on November 13, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.