C# Error CS0170 – Use of possibly unassigned field ‘field’

C# Compiler Error

CS0170 – Use of possibly unassigned field ‘field’

Reason for the Error

You will receive this error when C# compiler detected a field with-in a structure that was used without being initialized.

For example, the below code snippet will result with the error because the struct logData.Level was not initialized.

using System;

namespace ConsoleApp2
{
    public struct Log
    {
        public int Level ;
    }
    class Program
    {
        public static void Main()
        {
            Log logData;
            Console.WriteLine(logData.Level);
                 
        }

    }
    
}
C# Error CS0170 – Use of possibly unassigned field 'field'

Error CS0170 Use of possibly unassigned field ‘Level’ ConsoleApp2 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp2\Program.cs 14 Active

Solution

Ensure that you identify and initialize the struct variable that was uninitialized before its usage. The above code can be fixed as follows.

using System;

namespace ConsoleApp2
{
    public struct Log
    {
        public int Level ;
    }
    class Program
    {
        public static void Main()
        {
            Log logData;
            logData.Level = 1;
            Console.WriteLine(logData.Level);
                 
        }

    }
    
}
Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Hey, wait!Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.