DEV Community

Wriju's Blog
Wriju's Blog

Posted on

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

Discussion (0)