C# Error CS0199 – Fields of static readonly field ‘name’ cannot be passed ref or out

C# Compiler Error

CS0199 – Fields of static readonly field ‘name’ cannot be passed ref or out (except in a static constructor)

Reason for the Error

You will receive this error when you are trying to pass the static readonly field to a function outside of the constructor in your C# program.

For example, try to compile the below code snippet.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public static readonly int Id;
        static void SetId(ref int refId)
        {
            refId = 0;
        }
        public void InitializeEmployee()
        {
            SetId(ref Id);   // CS0199  
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

        }
    }

}

This program has a static readonly field Id in the Employee class. We are trying to pass this field to the SetId’s ref parameter inside the InitializeEmployee function. This results in the CS0199.

Error CS0199 A static readonly field cannot be used as a ref or out value (except in a static constructor) ConsoleApp3 C:\Users\SenthilBalu\source\repos\ConsoleApp3\ConsoleApp3\Program.cs 12 Active

C# Error CS0199 - Fields of static readonly field 'name' cannot be passed ref or out

Solution

To fix the error code CS0199, You can will need to ensure that you call the ref or out parameter of the function by passing the readonly static field only with-in the static constructor. The other option is to revisit your readonly static field and making them static instead of readonly static.

namespace DeveloperPubNamespace
{
    class Employee
    {
        public static readonly int Id;
        static void SetId(ref int refId)
        {
            refId = 0;
        }
        static Employee()
        {
            SetId(ref Id);   // CS0192  
        }
    }
    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...