C# Error CS1922 – Cannot initialize type ‘{0}’ with a collection initializer because it does not implement ‘System.Collections.IEnumerable’

C# Error

CS1922 – Cannot initialize type ‘{0}’ with a collection initializer because it does not implement ‘System.Collections.IEnumerable’

Reason for the Error & Solution

Collection initializer requires its type ‘type’ to implement System.Collections.IEnumerable.

In order to use a collection initializer with a type, the type must implement IEnumerable. This error can occur if you accidentally use collection initializer syntax when you meant to use an object initializer.

To correct this error

  • If the type does not represent a collection, use object initializer syntax instead of collection initializer syntax.

  • If the type does represent a collection, modify it to implement IEnumerable before you can use collection initializers to initialize objects of that type.

  • If the type represents a collection and you do not have access to the source code, just initialize its elements by using their class constructors or other initialization methods.

Example

The following code produces CS1922:

// cs1922.cs
public class Test
{
    public static void Main()
    {
        // Collection initializer.
        var tc = new TestClass  {1,"hello"} ; // CS1922

        // Object initializer.
        var tc2 = new TestClass { memberA = 1, memberB = "hello" }; // OK
    }
}

public class TestClass
{
    public int memberA { get; set; }
    public string memberB { get; set; }
}

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