DEV Community

Wriju's Blog
Wriju's Blog

Posted on

6 3

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

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs