Collection and List (Tip on When to Use What)

Here, I am not going to touch what a List is and what a collection is, instead of getting into the basics, let's have a look into today's tip.

Let's have a look at this snippet:

static void Main(string[] args)

{

    var originalData = new List<int> { 1, 2, 3, 4, 5, 6 };

    var listOfIntegers = new List<int>(originalData);

    var collectionOfIntegers = new Collection<int>(originalData);

    originalData.RemoveAt(0);

    PrintValue(listOfIntegers, "List: ");

    Console.WriteLine();

    PrintValue(collectionOfIntegers, "Collection: ");

    Console.ReadLine();

}

private static void PrintValue(IEnumerable<int> items, string from)

{

    Console.WriteLine(from);

    foreach (var item in items)

    {

        Console.WriteLine(item);

    }

    Console.WriteLine();

}

At first, most of you may feel that both the List and the Collection will contain print numbers from 1 to 6. Am I right?

But Alas! There is a hidden catch in it ;)

Because the actual output is:



What happened, surprised???

If you have ever tried to dig deep in the Collection and the List, then maybe you do know what the answer is. Well, the answer is pretty simple. MSDN documentation clearly states that "Initializes a new instance of the Collection class as a wrapper for the specified list".

And on the other hand, MSDN documentation states that "Initializes a new instance of the List<T> class that contains elements copied from the specified collection and has sufficient capacity to accommodate the number of elements copied."

Hope now it is clear to you.

So, the moral of the story is, one should be very cautious while using the List and Collection, else it can bite you extremely bad.