C# Error
CS1950 – The best overloaded Add method ‘{0}’ for the collection initializer has some invalid arguments
Reason for the Error & Solution
The best overloaded Add method ‘name’ for the collection initializer has some invalid arguments.
To support collection initializers, a class must implement IEnumerable and have a public Add
method. To initialize the type by using a collection initializer, the input parameter of the Add
method must be compatible with the type of the object you are trying to add.
To correct this error
-
Use a compatible type in the collection initializer.
-
Modify the input parameter and/or accessibility of the
Add
method in the collection type. -
Add a new
Add
method with an input parameter that matches what you are passing in. -
Make your collection class generic so that it can have an
Add
method that accepts any type you pass in.
Example
The following example generates CS1950:
// cs1950.cs
using System.Collections;
class TestClass : CollectionBase
{
public void Add(int c)
{
}
}
class Test
{
static void Main()
{
TestClass t = new TestClass { "hi" }; // CS1950
}
}