Default Values for Getter-Only Properties in C#: Simplifying Object Initialization

Learn how to assign default values to getter-only properties in C#. This guide explains how to initialize read-only properties, improving code readability and simplifying object initialization. Examples are provided to illustrate best practices.



Default Values for Getter-Only Properties in C#

In C#, you can assign default values to getter-only properties. A getter-only property is read-only; you cannot change its value after the object is created. This feature simplifies object initialization and enhances code readability.

Understanding Getter-Only Properties

A getter-only property has only a `get` accessor; there's no `set` accessor. This makes the property read-only. The value is typically initialized either within the property declaration or in the class constructor.

Assigning Default Values

You assign a default value directly within the property declaration using an initializer:


public class MyClass {
    public string Name { get; } = "Default Name"; // Default value assigned here
}

Example 1: Accessing Default Values


public class Student {
    public string Name { get; } = "Rahul";
    public string Email { get; } = "rahul@example.com";
}

public class Example {
    public static void Main(string[] args) {
        Student student = new Student();
        Console.WriteLine(student.Name);  // Output: Rahul
        Console.WriteLine(student.Email); // Output: rahul@example.com
    }
}

Example 2: Attempting to Assign a Value (Error)

Trying to assign a value to a getter-only property results in a compile-time error:


student.Name = "John"; // Compile-time error: Cannot assign to read-only property