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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...