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

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