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
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
Rahul Kumar
Now, there is no need to generate a constructor. Take a look at the example below.
C# Example with auto-initialize property
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
We can prevent a property from being altered by utilizing the private modifier. Consider the example below.
C# Example with auto-initialize property
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
Rahul Kumar