HomeCSharpC# Error CS1920 – Element initializer cannot be empty

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

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