Default Values For Getter Only Properties

This feature allows us to set default values for the getters. The getter-only property is read-only property. We can't set a new value to this property.

Compiler reports an error: cannot be assigned at compile time, if we assign value explicitly.

C# Default value for getter-only property Example 1

Example

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; } = "Rahul kumar";
        public string Email { get; } = "rahul@abc.com";
    }
    public class PropertyInitializer
    {
        public static void Main(string[] args)
        {
            Student student = new Student();
            Console.WriteLine(student.Name);
            Console.WriteLine(student.Email);
        }
    }
}

Output

Output

Rahul kumar[email protected]

Let's see an example, what happen if we assign value explicitly.

C# Default value for getter-only property Example 2

Example

using System;
namespace CSharpFeatures
{
    class Student
    {
        public string Name { get; } = "Rahul kumar";
        public string Email { get; } = "rahul@abc.com";
    }
    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

Output

error CS0200: Property or indexer 'Student.Name' cannot be assigned to -- it is read only

Input Required

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