Record Type in C#
Record type
Record can be class or struct.
Class is default and it need not be defined.
public record class Person(string FullName, DateOnly DateOfBirth);
equivalent to saying
public class Person{
public string FullName {get; init;} = default!;
public DateOnly DateOfBirth {get; set;}
}
public record struct Person(string FullName, DateOnly DateOfBirth);
Console.WriteLine(new Person{ FullName = "Kirthiga", DateOfBirth = new DateOnly(1996, 8, 7)};
It will say NameSpace.Person but won't say the details
var kirthiga = new Person("Kirthiga", new DateOnly(1996,8,7));
On the other hand when you use record and do a Console.WriteLine(kirthiga);
It will print out Person {FullName = "Kirthiga", DateOfBirth = "07/08/1996"} with full details
Also when we duplicate classes example,
var personA = new Person{
FullName = "Kirthiga",
DateOfBirth = "07/08/1996"
}
var personB = new Person{
FullName = "Kirthiga",
DateOfBirth = "07/08/1996"
}
Console.WriteLine(personA == personB); // will return false and it is comparing reference type.
But in case of records this will be true if they have the same properties.
Console.WriteLine(kirthiga1 == kirthiga2); // return true if you want to check reference
go for
Console.WriteLine(ReferenceEquals(kirthiga1, kirthiga2)); // return false
Kirthiga's twin
var mithila = kirthiga with {FullName = "mithila"};
Console.WriteLine(mithila);
Deconstructor
var (name, dateOfBirth) = mithila;
Console.WriteLine(name);
Console.WriteLine(dateOfBirth);
The properties are deconstructed.
The value of a record is immutable as we have init in props
public record Person(string FullName, DateOnly DateOfBirth)
{
protected virtual bool PrintMembers(StringBuilder builder)
{
builder.Append($"FullName is : {FullName} and the dateofBirth is : {DateOfBirth}");
return true;
}
}
SharpLab is a .NET code playground that shows intermediate steps and results of code compilation. Some language features are thin wrappers on top of other features -- e.g. using()
becomes try/finally
. SharpLab allows you to see the code as compiler sees it, and get a better understanding of .NET languages.
public void Deconstruct(out string FullName, out DateOnly DateOfBirth)
{
FullName = this.FullName;
DateOfBirth = this.DateOfBirth;
}
Also can be easily serialised and deserialised.
using System.Text.Json;
jsonString = JsonSerializer.Serialize(kirthiga);
Console.WriteLine(jsonString);
var recKirthiga = JsonSerializer.Deserialize(jsonString);
Console.WriteLine(recKirthiga);
Will use the PrintMembers
The virtual
keyword is used to modify a method, property, indexer, or event declaration and allow for it to be overridden in a derived class.
Comments
Post a Comment