HomeCSharpC# Error CS0820 – Cannot initialize an implicitly-typed variable with an array initializer

C# Error CS0820 – Cannot initialize an implicitly-typed variable with an array initializer

C# Error

CS0820 – Cannot initialize an implicitly-typed variable with an array initializer

Reason for the Error & Solution

Cannot assign array initializer to an implicitly typed local

An implicitly typed array is an array whose element type is inferred by the compiler. It must be initialized by using the new[] modifier as shown in the example code.

To correct this error

  • Use the new[] modifier with the array initializer.

  • Do not use an implicitly typed local variable.

Example

The following code generates CS0820 and shows how to correctly initialize an implicitly typed array:

//cs0820.cs  
class G  
{  
    public static int Main()  
    {  
  
        var a = { 1,2,3}; //CS0820  
        // Try using one of the following lines instead.  
        // var b = new[] { 1, 2, 3 };
       //int[] b = {1, 2, 3};  
        return -1;  
    }  
}  

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