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

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