C# Error CS0623 – Array initializers can only be used in a variable or field initializer. Try using a new expression instead.

C# Error

CS0623 – Array initializers can only be used in a variable or field initializer. Try using a new expression instead.

Reason for the Error & Solution

Array initializers can only be used in a variable or field initializer. Try using a new expression instead.

An attempt was made to initialize an array by using an array initializer in a context where it is not allowed.

Example

The following example produces CS0623 because the compiler interprets the {4} as embedded array initializer inside the outer array initializer:

//cs0632.cs  
using System;  
  
class X  
{  
    public int[] x = { 2, 3, {4}}; //CS0623  
}  

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