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

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...