Thursday, August 8, 2024

C# Record type: Something to remember while using record types

 

Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with class or struct declaration. 

There are two ways to declare records 

public record class Person(string FirstName,  int Age);

or we can define properties explicitly like

public record class Person{

    public string Name{get;set;}

    public int Age{get;set;}

}

var p1=new Person("Niranjan", 30);

var p2=new Person("Niranjan",30)

if we will compare p1 and p2 ,it will return true.

if(p1==p2) //true ; while in case of class it will return false.

Points to remember:

  • If records declared with primary constructor syntax, they will be immutable. we can change properties and get new record instance using 'with' keywords.
  • record overides ToString(),ToEqual(), GetHashCode() and implements destructing.
  • using .ToString with records prints all properties with name and value.
  •  record overriddes ToEqual() methods uses IEquatable<T> interface to compare preparties values so it's necessary to use property datatype which implements IEquatable<T> in order to get successful value comparison for two records.
Example:

public records class Employee(string Name, int Age, List<string> Addresses);

var e1=new Employee("Raj",30,new List<string>{"A1","A2"});
var e2=new Employee("Raj",30,new List<string>{"A1","A2"});

if(e1==e2) // will return false as List<string> does not implement IEquatable<T> interface. 

C# Record type: Something to remember while using record types

  Record in c# provide a concise and expressive way to create immutable data types, record is a keyword in c#, we can use this keyword with ...