C# Error CS0838 – An expression tree may not contain a multidimensional array initializer

C# Error

CS0838 – An expression tree may not contain a multidimensional array initializer

Reason for the Error & Solution

An expression tree may not contain a multidimensional array initializer.

Multidimensional arrays in expression trees cannot be initialized by using an array initializer.

To correct this error

  1. Create and initialize the array before creating the expression tree.

Example

The following example generates CS0838:

// cs0838.cs  
using System;  
using System.Linq;  
using System.Linq.Expressions;  
  
namespace TestNamespace  
{  
    class Test  
    {  
        static int Main()  
        {  
  
            Expression<Func<int[,]>> expr =  
                () => new int[2, 2] { { 1, 2 }, { 3, 4 } }; // CS0838  
  
            // try the following 2 lines instead  
            int[,] nums = new int[2, 2] { { 1, 2 }, { 3, 4 } };  
            Expression<Func<int[,]>> expr2 = () => nums;
  
            return 1;  
        }  
    }  
}  

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