-1

I have this class:

class Salaries : IEnumerable
{
    List<double> salaries = new List<double>();

    public Salaries()
    {
    }

    public void Insert(double salary)
    {
        salaries.Add(salary);
    }

    public IEnumerator GetEnumerator()
    {
        return salaries.GetEnumerator();
    }
}

In the program I try to add some values like this:

Salaries mySalaries = new Salaries() { 1000, 2000, 3000 };

I get this error:

'Salaries' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'Salaries' could be found (are you missing a using directive or an assembly reference?)

Why do I get this error?

Where can I find (using VS) that I need to implement Add function?

If I look in the List definition, I can see more functions, so why the compiler wants me to implement Add?

(I know that if I change the method in the class from Insert to Add it's OK. But the question is why only add, and where does it come from?)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Noam B.
  • 3,120
  • 5
  • 25
  • 38
  • Possible duplicate of [How can I add an item to a IEnumerable collection?](http://stackoverflow.com/questions/1210295/how-can-i-add-an-item-to-a-ienumerablet-collection) – Idos Feb 21 '16 at 11:18
  • 1
    Why don't you just rename Insert to Add and get it over with? It is a misleading name anyway since it doesn't actually "insert", it only appends. – Hans Passant Feb 21 '16 at 12:31
  • Please read my post again. Especialy the last part. – Noam B. Feb 21 '16 at 12:41
  • 1
    Please read my comment again. Especially the last part. The only thing you can do wrong is not trying it. – Hans Passant Feb 21 '16 at 13:02

1 Answers1

5

Because you are calling the Add method when you use a collection initializer.

Salaries mySalaries = new Salaries() { 1000, 2000, 3000 };

is translated by the compiler to:

Salaries mySalaries = new Salaries();
mySalaries.Add(1000);
mySalaries.Add(2000);
mySalaries.Add(3000);
Dennis_E
  • 8,751
  • 23
  • 29