DEV Community

Wriju's Blog
Wriju's Blog

Posted on • Edited on

C# 9.0 Optional Property in Record

In C# 9.0 record can be declared in two different ways. One with the property and other without. The second one is more concise and would automatically add the property.

This is how you can declare with property,

//Call
var emp = new Employee()
{
    FirstName = "Wriju",
    LastName = "Ghosh"
};
Console.WriteLine("With Property : {0} {1}", emp.FirstName, emp.LastName);

//Record with property
record Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

This can be simplified,

var emp1 = new Employee()
{
    FirstName = "Wrishika",
    LastName = "Ghosh"
};
Console.WriteLine("Without Property : {0} {1}", emp1.FirstName, emp1.LastName); 

//record without explicit property
record Employee1 (string FirstName, string LastName);
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
peledzohar profile image
Zohar Peled

Side note: You should probably not use setters in record type properties - as being immutable is kind of the main point of record in the first place.

C# 9.0 introduces record types, which are a reference type that provides synthesized methods to provide value semantics for equality. Records are immutable by default.

You should probably change

record Employee
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

to

record Employee
{
    public string FirstName { get; init; }
    public string LastName { get; init; }
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
wrijugh profile image
Wriju's Blog

I have addressed this already in my previous blog dev.to/wrijugh/c-9-0-init-only-pro...

Collapse
 
peledzohar profile image
Zohar Peled

Yeah, I've seen your post about init only properties, but that's not the point of my comment - the point is that (IMHO) records shouldn't have setters on their properties.