This functionality enables us to define initial values for the accessors. The accessor-only attribute acts as a read-only attribute, preventing any modifications to its value.
Compiler generates an error when attempting to assign a value explicitly that cannot be done at compile time.
C# Default value for getter-only property Example 1
using System;
namespace CSharpFeatures
{
class Student
{
public string Name { get; } = "Rahul kumar";
public string Email { get; } = "[email protected]";
}
public class PropertyInitializer
{
public static void Main(string[] args)
{
Student student = new Student();
Console.WriteLine(student.Name);
Console.WriteLine(student.Email);
}
}
}
Output
Rahul kumar[email protected]
Let's consider an example to understand the outcome when assigning a value explicitly.
C# Default value for getter-only property Example 2
using System;
namespace CSharpFeatures
{
class Student
{
public string Name { get; } = "Rahul kumar";
public string Email { get; } = "[email protected]";
}
public class PropertyInitializer
{
public static void Main(string[] args)
{
Student student = new Student();
Console.WriteLine(student.Name);
Console.WriteLine(student.Email);
student.Name = "john";
Console.WriteLine(student.Name);
}
}
}
Output
error CS0200: Property or indexer 'Student.Name' cannot be assigned to -- it is read only