Record in C#9

shalini Pahwa

--

C# 9.0 introduces record types. You can use the record keyword to define a reference type that support inheritance and have immutable properties.

Example

public record Employee(int id, string Name, string Location, float Salary);

Inheritance

public record Person(string Name, int Age);public record Student (string Name, int Age ,string University, string course) : Person(Name, Age);

Can be abstract

public abstract record Person(string Name, int Age);

You can use it in List

public record Employee(int id, string Name, string Location, float Salary);public readonly List<Employee> _contacts = new List<Employee>{new (1, “Ronald”, “AL”,1000),new (2, “Annie”, “AR”, 10000),new (3, “Aaron”, “FL”, 100000),new (4, “Joseph”, “GA”,1000000),new (5, “Jasmine”, “AZ”,1000000)};

With Expression

Creating new Record with some properties changed.

var p1 = new Person(“Henary”, 30);var p2 = p1 with { Name = “Jon”};Console.WriteLine(p1);//Person { Name = Henary, Age = 30 }Console.WriteLine(p2);//Person { Name = Jon, Age = 30 }

Equality

//classesPersonClass a = new(“Tom”, 30);PersonClass b = new(“Tom”, 30);Console.WriteLine($”a.Equals(b)= {a.Equals(b)}”); //return false//recordsvar r1 = new Person(“Jim”, 30);var r2 = new Person(“Jim”, 30);Console.WriteLine($”r1.Equals(r2) {r1.Equals(r2)}”);// TrueConsole.WriteLine($”r1 == r2 {r1 == r2}”);//TrueConsole.WriteLine($”ReferenceEquals(r1, r2)= {ReferenceEquals(r1, r2)}”); //return false

Immutability

I tested it 2–3 ways. Here is my findings.

Immutable

public record Person(string Name, int Age);//is immutablevar p1 = new Person(“Jim”, 30);p.Name=”Henery”;//not possible

Mutable

public record student{public string Name { get; set; }public int Age { get; set; }}var s=new student{Name=”Henery”,Age=90};s.Age=30;//possible

Immutable with init

public record student{public string Name { get; init; }public int Age { get; init; }}var s=new student{Name=”Henery”,Age=90};s.Age=30;//not possible

Before adding Record type in your code consider following points

1. Use it when you want one way flow as its value oriented and immutable.

2. Don’t convert your complex class to record.

3. A reference type with immutable properties.

4. Has Value equality.

5. Support for inheritance hierarchies.

6. Built-in formatting.

7. Record is good for DTOs.

8. Thread safe as it is immutable.

9. Easy to share.

10. With-expression allows one to create a new instance of a record based on an existing record.

11. Use it to store data that doesn’t change.

12. Need hierarchical structure(inheritance).

13. Use it for API calls.

14. Store read-only data into it.

15. Don’t use it with entity framework.

16. Avoid making it mutable

Sign up to discover human stories that deepen your understanding of the world.

--

--

No responses yet

Write a response