HomeCSharpC# Error CS1954 – The best overloaded method match ‘{0}’ for the collection initializer element cannot be used. Collection initializer ‘Add’ methods cannot have ref or out parameters.

C# Error CS1954 – The best overloaded method match ‘{0}’ for the collection initializer element cannot be used. Collection initializer ‘Add’ methods cannot have ref or out parameters.

C# Error

CS1954 – The best overloaded method match ‘{0}’ for the collection initializer element cannot be used. Collection initializer ‘Add’ methods cannot have ref or out parameters.

Reason for the Error & Solution

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.

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

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

This C# program calculates and displays an upper triangular matrix based on user input. Problem Statement: The program takes the...
This C# program serves as a demonstration of bitwise operators, which are fundamental operators used for manipulating individual bits in...
This C# program is designed to interchange or swap the columns of a matrix. A matrix is a two-dimensional array...