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; }
}
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);
Top comments (3)
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.
You should probably change
to
I have addressed this already in my previous blog dev.to/wrijugh/c-9-0-init-only-pro...
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.