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);
                 
        }

    }
    
}

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...