C# Error CS0191 – Property or indexer ‘name’ cannot be assigned to — it is read only

C# Compiler Error

CS0191 – Property or indexer ‘name’ cannot be assigned to — it is read only

Reason for the Error

You will receive this error when you try to assign a value to the readonly property in a function. In C#, the readonly fields can only be assigned during the declaration or in a constructor.

For example, try to compile the below code snippet.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public readonly int Id;

        Employee()
        {
        }

        public void InitializeEmployee(int id)
        {
            Id = id;         
        }
    }
    class Program
    {      
        static void Main(string[] args)
        {

        }    
    }
  
}

The above code snippet will result with the C# error code CS0191 because Id is a readonly field and this field is been assigned a value in the function InitializeEmployee.

Error CS0191 A readonly field cannot be assigned to (except in a constructor or init-only setter of the type in which the field is defined or a variable initializer) ConsoleApp3 C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 13 Active

C# Error CS0191 - Property or indexer 'name' cannot be assigned to -- it is read only

Solution

To fix the error, ensure that the readonly fields are only assigned inside the constructor or during the declaration in C#. Below is a sample code snippet demonstrating how to fix the error code CS0191.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public readonly int Id;

        Employee(int id)
        {
            Id = id;
        }

        public void InitializeEmployee(int id)
        {
                  
        }
    }
    class Program
    {      
        static void Main(string[] args)
        {

        }    
    }
  
}

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...