In C#, an init-only property is a feature introduced in C# 9.0 as part of the record types feature. It allows you to define properties that can only be set during object initialization or within the constructor of the containing type. After the object is initialized, the property becomes read-only and cannot be modified.
Here's an example of how to declare an init-only property:
public class Person
{
public string FirstName { get; init; }
public string LastName { get; init; }
public Person(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
// Usage
var person = new Person("John", "Doe");
Console.WriteLine($"Full Name: {person.FirstName} {person.LastName}");
// This would be an error since the property is init-only and cannot be modified after initialization.
// person.FirstName = "Jane";
In this example, the FirstName and LastName properties are declared as init-only properties using the init accessor. They can only be set during object initialization through the constructor. After the object is initialized, attempting to modify these properties will result in a compilation error.
Init-only properties are useful for scenarios where you want to enforce that certain properties are set only once, typically during object construction, and then remain immutable throughout the object's lifetime. This helps in creating more predictable and maintainable code.
No comments:
Post a Comment