HomeCSharpC# Error CS0198 – Fields of static readonly field ‘name’ cannot be assigned to

C# Error CS0198 – Fields of static readonly field ‘name’ cannot be assigned to

C# Compiler Error

CS0198 – Fields of static readonly field ‘name’ cannot be assigned to (except in a static constructor or a variable initializer)

Reason for the Error

You will receive this error when you are trying to initialize a static field in Non-Static constructor in your C# program.

For example, try to compile the below code snippet.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public static readonly int Id;

        Employee()
        {
            Id = 10;  
        }
    }
    class Program
    {
        static void Main(string[] args)
        {


        }
    } 
}

This program has a static readonly field Id in the Employee class. There is a non-static constructor where we are trying to initialize the static field Id to 10. This will result in the error code CS0198.

Error CS0198 A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) ConsoleApp3 C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 9 Active

Solution

To fix the error code CS0198, ensure that you initialize the static fields in the static constructors in your C# code.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public static readonly int Id = 6;
        static Employee()
        {
            Id = 11;  
        }
    }
    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...