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