Hello Friends,
In C# 9.0, there is a new type 'record' has been introduced and believe me, I was very excited when I see this feature. As a programmer I got many situation where I had to do a lot to compare two class objects to check if they both have same values, cloning a class and used to think why can’t be this made simpler.
And here we go, Now C# 9.0 has introduced record types to fulfil the need of value based equality, comparisons with reference variables. So the difference between a class and record type are:
1. Both are reference type but record type equality is determined by the equality of values of the data members where as class does the comparison with reference.
Yeah and that is all the difference I see between a class and record type. ❤
I was playing a bit to figure out what we can do with record type and below code shows all interesting stuff or need which we want as a programmer. So let’s go one by one.
- Is record type supports interface inheritance: Yes It does.
- Is record type support inheritance: Yes It does.
- Can we clone the object of record type: Aha, it supports C# 9.0 ‘with’ expression which allows to easily clone the object.
- It really compares values: Yes it does.
- Last but not the list, Everyone would love it for tracing (no more serializing).
public interface IHuman
{
string Family { get; }
}
public record Person : IHuman
{
public string Family => "Hominidae";
public string FirstName { get; init; }
public string LastName { get; init; }
}
Note: record type too support init-only feature of C# 9.0 which is equivalent to ReadOnly. In above code I have mentioned init only setter property for FirstName and LastName which means these values must be initialized while object initialization and can’t be modified after that.Also you can introduced new record types with inheritance simply with a line of code:public record Actor : Person
{
public int Age { get; set; }
public Gender Gender { get; init; } public void PrintActorDetails()
{
Console.WriteLine($"Name:{FirstName} {LastName}, Age:{Age}, Gender:{Gender}");
}
}
public record Bollywood(string Industry) : Actor;
This means, the new Bollywood record type has a new member called Industry which is required while creating a new object of record type Bollywood. Interesting Isn’t it. I ❤ it.var actor1 = new Actor { FirstName = "Varun", LastName="Dhawan", Age=30, Gender=Gender.Male }; var actor2 = actor1 with { FirstName = "Akshay", LastName= "Kumar" };
var actor1 = new Actor { FirstName = "Varun", LastName="Dhawan", Age=30, Gender=Gender.Male };
var actor2 = actor1 with { Age = 30 };
Console.WriteLine(actor1.Equals(actor3));// results true.
var bollyActor = new Bollywood("Bollywood") { Age = 30, FirstName = "Kiara", LastName = "Advani", Gender = Gender.Female };
Console.WriteLine(bollyActor);
Above code will result output as:
No comments:
Post a Comment