Exploring C# 9 Features: Records, and Init-only Setters
Exploring C# 9 Features: Records, and Init-only Setters
As a C# developer, staying updated with the latest language features can greatly enhance your coding efficiency. Let's delve into two key features introduced in C# 9: Records and Init-only setters.
Records: Simplifying Immutable Data Types
Records are a new type in C# 9 designed to simplify the creation of immutable data types. Here's how you can define a Record:
public record Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
}
// Creating a new Person record
var person = new Person
{
FirstName = "John",
LastName = "Doe"
};
In this example, the 'init' keyword in property declarations signifies that these properties can only be set during object initialization. The compiler automatically generates methods like Equals, GetHashCode, and ToString for the Person record, making it easier to work with immutable data.
Init-only Setters: Enhanced Immutability
Init-only setters complement Records by allowing properties to be set only during object initialization. Consider the following example:
public class Product
{
public string Name { get; init; }
public decimal Price { get; init; }
}
// Creating a new Product with init-only setters
var product = new Product
{
Name = "Laptop",
Price = 999.99m
};
Once an object is initialized, attempts to modify the 'Name' and 'Price' properties will result in compilation errors, enforcing the object's immutability and improving code reliability.
Differences between Records and Init-only Setters:
- Records: Automatically generate equality checks, hash code generation, and string representations. Ideal for creating immutable data types with minimal boilerplate code. Use Records when you need to define data-centric types that are immutable.
- Init-only Setters: Restrict property modifications after object initialization, ensuring immutability and preventing accidental changes, but do not automatically generate additional methods like Records. Use Init-only setters when you want to enforce immutability for specific properties within a class.
These features exemplify C#'s dedication to enhancing developer productivity and code quality. Stay tuned for more updates advanced programming techniques!

Comments
Post a Comment