Hello everyone! Hope everything is fine. Today I am going to discuss about why we should use C# records instead of classes.
What are Record?
From C# 9, records are new type defined as reference type using record keyword. They are immutable which means once created it cannot be changed.
Record type already overrides both virtual ToString and Equals method on the Object base class.
public record class Person(string firstName, string lastName)
public record Person{
public String firstName {get; set;}
public String lastName {get; set;}
};
Use of class keyword is optional
IN C# 10, records are introduced as struct type which defines record as value type.
public readonly record struct Point(double X, double Y, double Z)
public record struct Point{
public double X {get; set;}
public double Y {get; set;}
public double Z {get; set;}
};
Equality
Records are value type unlike class type, So two record variable are said to be equal if they have same record type definition and values are equal in two records.
on the other hand two class type variable are said to be equal if they have same class type definition and both are pointing to same object.
Let's look at example
public record struct Point{
public Point(double pt1, double pt2, double pt3){
X = pt1;
Y = pt2;
Z = pt3;
}
public double X {get; set;}
public double Y {get; set;}
public double Z {get; set;}
};
And then we will create variables of those records
public class Main{
public static void main(){
Point p1 = new Point(5.0, 10.0, 1);
Point p2 = new Point(15.0, 10.0, 0);
Point p3 = new Point(5.0, 10.0, 1);
if(p1 == p2)
Console.log("p1 and p2 are Equal");
if(p1 == p3)
Console.log("p1 and p3 are Equal");
}
}
Below we are going to see same example using classes
public class Main{
public static void main(){
Point p1 = new Point(5.0, 10.0, 1);
Point p2 = new Point(15.0, 10.0, 0);
Point p3 = p1;
if(p1 == p2)
Console.log("p1 and p2 are Equal");
if(p1 == p3)
Console.log("p1 and p3 are Equal");
}
}
//Output : p1 and p3 are Equal
Immutability
Records are designed to be immutable unlike classes, Once records are instantiated they cannot be changed.
Records do support nondestructive mutation by using keyword with
public static void Main(){
Person employee1 = new Person("John", "Doe");
Person employee2 = employee1 with {firstName = "Martin"};
Console.WriteLine(employee1.firstName + " "+
employee1.lastName);
//John Doe
Console.WriteLine(employee2.firstName + " "+
employee1.lastName);
//Martin Doe
}
Concise code
We have already discussed short hand way(single line declaration) of writing records. Less code means smaller codebase and easy maintenance.
Records are generally used for handling data and classes defines behaviors.
That's all for today, Happy coding!...