Default Values For Getter Only Properties - C# Tutorial
C# Course / Version Features / Default Values For Getter Only Properties

Default Values For Getter Only Properties

BLUF: Mastering Default Values For Getter Only Properties 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: Default Values For Getter Only Properties

C# is a powerful, modern language for enterprise solutions. Discover how Default Values For Getter Only Properties enhances your development workflow in the guide below.

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

Example

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

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

Example

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

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:

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