C# auto-initialize property is a feature, introduced in 6.0. It allows us to initialize properties without creating a constructor.
Now, we can initialize properties along with declaration.
In early versions, constructor is required to initialize properties. An old approach is used in the following example.
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, we don't need to create constructor. See, the following example.
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 make a property restrict to change by setting private modifier. See, the following example.
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