C# Error CS0573 – ‘field declaration’ : cannot have instance field initializers in structs

C# Compiler Error

CS0573 – ‘field declaration’ : cannot have instance field initializers in structs

Reason for the Error

You will get this error in your C# code when you are trying to initialize an instance field inside a struct.

For example, let’s compile the below C# program

using System;

namespace DeveloperPublishConsoleCore
{
    public struct Employee
    {
        int Id = 7;   // Error Code        
    }

    internal class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("DeveloperPublish Hello World!");
        }
    }
}

You will receive the error code CS0573 because you are trying to initialize the field “Id” inside Employee class.

error CS0573: ‘DeveloperPublishConsoleCore.Employee’: Structs cannot have instance property or field initializers

C# Error CS0573 – 'field declaration' : cannot have instance field initializers in structs

You will not receive this error in C# 10 and higher versions as it contains “struct field initializers”.

Alternatively, you may also receive the below error depending on the version of Visual Studio and C# language that you are using.

Error CS8400 Feature ‘struct field initializers’ is not available in C# 8.0. Please use language version 10.0 or greater. DeveloperPublishConsoleCore C:\Users\senth\source\repos\DeveloperPublishConsoleCore\DeveloperPublishConsoleCore\Program.cs

C# Error CS0573 – 'field declaration' : cannot have instance field initializers in structs

Solution

You can fix this error in your program by either using C# 10.0 or higher or removing the explicit initialization of the field inside struct.

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...