C# Error CS1063 – The best overloaded Add method ‘{0}’ for the collection initializer element is obsolete. {1}

C# Error

CS1063 – The best overloaded Add method ‘{0}’ for the collection initializer element is obsolete. {1}

Reason for the Error & Solution

The best overloaded Add method for the collection initializer element is obsolete.

This error occurs when a type that implements IEnumerable implements one or more Add methods but the best matching overload is attributed with ObsoleteAttribute and the ObsoleteAttribute.IsError property is initialized to true.

Example

The following sample generates CS1063:

// CS1063.cs (9,38)
using System;
using System.Collections;

class Test
{
    public static void Main()
    {
        B coll = new B { "a" };
    }
}

public class B : IEnumerable
{
    [Obsolete("Don't use this overload", true)]
    public void Add(string s)
    {
        //...
    }
    public void Add(int i)
    {
        //...
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return null;
    }
}

To correct this error

If you own the enumerable type code and want to utilize a collection initializer, remove the ObsoleteAttribute.

public class B : IEnumerable
{
    public void Add(string s)
    {
        //...
    }
    public void Add(int i)
    {
        //...
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return null;
    }
}

If you do not own the enumerable type code, you will have to choose another means to initialize the collection.

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