Compiler Error CS1925
Cannot initialize object of type 'type' with a collection initializer.
Collection initializers are only allowed for collection classes that meet certain criteria. For more information, see Object and Collection Initializers (C# Programming Guide). This error is also produced when you try to use the short form of an array initializer nested inside a collection initializer.
To correct this error
- Initialize the object by calling its constructors and methods.
Example
The following code generates CS1925:
// cs1925.cs
public class Student
{
public int[] Scores;
}
class Test
{
static void Main(string[] args)
{
//Student student = new Student { Scores = { 1, 2, 3 } }; // Causes CS1925.
// Use the default constructor, then initialize the array separately.
Student student1 = new Student();
student1.Scores = new[] { 1, 2, 3 };
// Use an object initializer to create and initialize the object.
Student student2 = new Student { Scores = new[] { 1, 2, 3 } };
}
}
Change History
Date |
History |
Reason |
---|---|---|
May 2010 |
Expanded the code example to illustrate how to fix the problem. |
Customer feedback. |