C# Error CS1920 – Element initializer cannot be empty

C# Error

CS1920 – Element initializer cannot be empty

Reason for the Error & Solution

Element initializer cannot be empty.

A collection initializer consists of a sequence of element initializers. The element initializers do not have to be enclosed in braces unless they contain an assignment expression. However, if you do supply braces, they cannot be empty. If the element initializer is an object initializer, the braces may be empty as long as the initializer contains a new object creation expression.

To correct this error

  • Add the missing expression between the braces.

  • If the expression is intended to be an object initializer, add the new object creation expression in front of the braces.

Example

The following example generates CS1920:

  // cs1920.cs  
using System.Collections.Generic;  
public class Test  
{  
    public static int Main()  
    {  
        // Error. Empty initializer
        // for inner list.  
        List<List<int>> collection =  
            new List<List<int>>() { { } }; // CS1920  
  
        // OK. No initializer for inner list.  
        List<List<int>> collection2 =  
            new List<List<int>>() {  };  
  
        // OK. Inner list is initialized
        // to one List<int> with zero elements.  
        List<List<int>> collection3 =  
            new List<List<int>>() { new List<int> { } };  
        return 0;  
    }  
}  

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