C# Error CS0846 – A nested array initializer is expected

C# Error

CS0846 – A nested array initializer is expected

Reason for the Error & Solution

A nested array initializer is expected

This error occurs when something other than an array initializer is used when creating an array.

Example

The following sample generates CS0846:

// CS0846.cs (0,0)

namespace Test
{
    public class Program
    {
        public void Goo()
        {
            var a3 = new[,,] { { { 3, 4 } }, 3, 4 };
        }
    }
}

To correct this error

This example contains a 3-dimensional array. The initializer does not represent a three-dimensional array, resulting in CS0846. The last two statements in the top-level array initializer , 3, 4 are not an array initializer. Assuming the intent is to create a 3-dimensional array with 2, 1, and 2 elements per dimension, to correct this error, properly bracket the last two statements:

        var a3 = new[, ,] { { { 3, 4 } }, { { 3, 4 } } };

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