2

First:

List <string> candidates = new List <string> {"person1", "person2"};

Second:

Queue <int> myQueue = new Queue <int>(new int [] {0, 1, 2, 3, 4});

Why we do NOT use parentheses while initializing a new list but we do for a queue or a stack?

JJJ
  • 32,902
  • 20
  • 89
  • 102
  • They are optional in the first statement. Just add them so you don't have to ask this question: `new List() {...};` Also the best way to see that the two statements have nothing in common. – Hans Passant May 25 '17 at 22:38

1 Answers1

1

With the list, you are taking advantage of a feature called "Collection initializers", you can read about it here: https://learn.microsoft.com/en-us/dotnet/articles/csharp/programming-guide/classes-and-structs/object-and-collection-initializers

Basically, to work, it depends on the collection implementing the IEnumerable interface and having an "Add" method (which Queue does not have), or, there being a reachable extension method called "Add" (which you could implement yourself for Queue).

    static class QueueExtensions
    {
        public static void Test()
        {
            // See that due to the extension method below, now queue can also take advantage of the collection initializer syntax.
            var queue = new Queue<int> { 1, 2, 3, 5 };
        }

        public static void Add<T>(this Queue<T> queue, T element)
        {
            queue.Enqueue(element);
        }
    }
Fredy Treboux
  • 3,167
  • 2
  • 26
  • 32
  • 1
    A more detailed explanation can be found here: https://stackoverflow.com/questions/8853937/why-can-i-initialize-a-list-like-an-array-in-c – Timo May 25 '17 at 22:27