Auto Property Initializers - C# Tutorial
C# Course / Version Features / Auto Property Initializers

Auto Property Initializers

BLUF: Mastering Auto Property Initializers is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Auto Property Initializers

C# is a powerful, modern language for enterprise solutions. Discover how Auto Property Initializers enhances your development workflow in the guide below.

C# auto-property initializer is a functionality introduced in version 6.0, enabling property initialization without the need for a constructor.

Now, properties can be initialized during declaration.

In previous iterations, it was necessary to utilize a constructor for initializing properties. The subsequent illustration demonstrates an outdated method.

C# Example without auto-initialize property

Example

using System;
namespace CSharpFeatures
{
    public class PropertyInitializer
    {
        public string Name { get; set; }
        PropertyInitializer()
        {
            Name = "Rahul Kumar";
        }
        public static void Main(string[] args)
        {
            PropertyInitializer pin = new PropertyInitializer();
            Console.WriteLine(pin.Name);
        }
    }
}

Output

Output

Rahul Kumar

Now, there is no need to generate a constructor. Take a look at the example below.

C# Example with auto-initialize property

Example

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

Output

Rahul Kumar

We can prevent a property from being altered by utilizing the private modifier. Consider the example below.

C# Example with auto-initialize property

Example

using System;
namespace CSharpFeatures
{
    class Student
    {
        // Auto-property initializer
        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

Output

Rahul Kumar

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience