C# 9.0 - Record Type

wrijugh

Wriju's Blog

Posted on November 13, 2020

C# 9.0 - Record Type

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);
    }
}
Enter fullscreen mode Exit fullscreen mode

To use as normal

var emp = new Employee ( 1, "Wriju" );

Console.WriteLine("{0} - {1}", emp.Id, emp.FullName);
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

You can also create a copy of the record with changed property value using with keyword.

var emp2 = emp with { FullName = "Wriju Ghosh" };
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
wrijugh
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.

Related

C# 9.0 - Record Type
csharp9 C# 9.0 - Record Type

November 13, 2020

C# 9.0 - Optional "Main"
csharp9 C# 9.0 - Optional "Main"

November 12, 2020