Auto-Initialized Properties in C#: Concise Property Initialization

Learn about auto-initialized properties in C#, a concise way to initialize properties directly in their declaration. This guide explains their syntax, usage, and how they simplify object initialization, leading to more compact and readable C# code.



Auto-Initialized Properties in C#

Introduction

Auto-initialized properties, introduced in C# 6.0, provide a concise way to initialize properties directly within their declaration. This eliminates the need for a constructor in many cases, leading to more compact and readable code.

Auto-Initialization Syntax

To auto-initialize a property, simply assign a value to it during the property declaration. This value is assigned when the object is created.

Auto-Initialized Property Syntax

public string Name { get; set; } = "Initial Value"; 

Example 1: Auto-Initialized Property

This example demonstrates auto-initialization without a constructor.

Example 1: Auto-Initialization

using System;

namespace CSharpFeatures {
    public class PropertyInitializer {
        public string Name { get; set; } = "Rahul Kumar";

        public static void Main(string[] args) {
            PropertyInitializer pin = new PropertyInitializer();
            Console.WriteLine(pin.Name); // Output: Rahul Kumar
        }
    }
}

Example 2: Read-Only Auto-Initialized Property

You can create read-only auto-initialized properties by making the setter `private`:

Example 2: Read-Only Auto-Initialization

using System;

namespace CSharpFeatures {
    class Student {
        public string Name { get; private set; } = "Rahul Kumar"; 
    }

    public class PropertyInitializer {
        public static void Main(string[] args) {
            Student student = new Student();
            Console.WriteLine(student.Name); // Output: Rahul Kumar
        }
    }
}

Comparison with the Older Approach

Before C# 6.0, you would typically initialize properties in a constructor. This required extra code:

Older Approach (Constructor Initialization)

using System;

namespace CSharpFeatures {
    public class PropertyInitializer {
        public string Name { get; set; }

        PropertyInitializer() {
            Name = "Rahul Kumar";
        }
        // ... rest of the class ...
    }
}

Conclusion

Auto-initialized properties offer a more concise and readable alternative to initializing properties within constructors. This improves code maintainability, especially when dealing with numerous properties. The ability to create read-only auto-initialized properties adds further flexibility to your class design.