How to Answer: C# 9.0 - What is an init-only setter?
Advice and answer examples written specifically for a C# Advanced job interview.
3. C# 9.0 - What is an init-only setter?
This interview question shows the developer's understanding of C# features.
This construct provides a clear, concise way of initializing a property. Properties defined in this way are read-only once defined. Attempting to change the property will result in a compiler error.
// Define a struct with the init setter
public struct Product
{
public decimal Price { get; init; }
public string ProductName{ get; init; }
public string SKU { get; init; }
}
// compiles fine
var shampoo = new Product
{
Price = 4.99M,
ProductName = "My Excellent Shampoo",
SKU = "FFH2209"
};
// Trying to change any of the properties after construction will result in an error as shown below
//Severity Code Description Project File Line Suppression State
//Error CS8852 Init - only property or indexer 'Program.Product.SKU' can only be assigned in an object
//initializer, or on 'this' or 'base' in an instance constructor or an
//'init' accessor.Active
shampoo.SKU = "FFLXI220";
Written by Edward Danganan on April 21st, 2021