Studies show that good grammar leads to more promotions and higher salaries. Write with Grammarly

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)
        {


        }
    } 
}