Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
The best overloaded method match 'method' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters.
For a collection class to be initialized by using a collection initializer, the class must have a publicAdd method that is not a ref or out parameter.
To correct this error
If you can modify the source code of the collection class, provide an Add method that does not take a ref or out parameter.
If you cannot modify the collection class, initialize it with the constructors it provides. You cannot use a collection initializer with it.
Example
The following example produces CS1954 because the only available overload of the Add list in MyList has a ref parameter.
// cs1954.cs
using System.Collections.Generic;
class MyList<T> : IEnumerable<T>
{
List<T> _list;
public void Add(ref T item)
{
_list.Add(item);
}
public System.Collections.Generic.IEnumerator<T> GetEnumerator()
{
int index = 0;
T current = _list[index];
while (current != null)
{
yield return _list[index++];
}
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public class MyClass
{
public string tree { get; set; }
}
class Program
{
static void Main(string[] args)
{
MyList<MyClass> myList = new MyList<MyClass> { new MyClass { tree = "maple" } }; // CS1954
}
}