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

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