Skip to main content

Silly but useful stuff - Part 1 (.Net)


Collection and List
Let's have a look at this snippet:























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

But Alas! There is a hidden gotcha in it ;)
Because the actual output is:







What happen surprised???

If you have ever tried to get in depth of Collection and List, then you might know the answer. Well, the answer is pretty simple. MSDNdocumentation 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 List and Collection else it can bite you really very-very hard.

Comments