Export (0) Print
Expand All
Expand Minimize

Compiler Error CS1954

Visual Studio 2008

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

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

Community Additions

ADD
Show:
© 2014 Microsoft