C# Error CS0171 – Field ‘name’ must be fully assigned before control is returned to the caller

C# Compiler Error

CS0171 – Field ‘name’ must be fully assigned before control is returned to the caller

Reason for the Error

You will receive this error in your C# code when you have used a struct with constructor for example and have NOT initialized all fields in the struct.

For example, try compiling the below code snippet

namespace DeveloperPublish
{
    struct Employee
    {
        Employee(int id) 
        { 
        }
        public int Id;
    }
    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
        }
    }
}

This will result with the error CS0171 as the field “Id” used in the struct “Employee” is not initialized in the constructor.

Error CS0171 Field ‘Employee.Id’ must be fully assigned before control is returned to the caller ConsoleApp3 C:\Users\Senthil\source\repos\ConsoleApp1\ConsoleApp3\Program.cs 6 Active

C# Error CS0171 – Field 'name' must be fully assigned before control is returned to the caller

Solution

To fix this error, ensure that all the fields are initialized inside the constructor of the struct.

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.