Some .NET Gotchas

1) For.. Each vs For...

I have often wondered what is the difference between for..each and for loops in iterating over collections, because I always use the regular for loops.

Today, I found out one major difference - if while iterating over the for..each, I add an item to the list being iterated, the for.. each loop will not go over this newly added item.

On the other hand, if I use a regular for loop using the length of the collection, and I add an item to the list, it will also get iterated over.

2) Using LINQ and unexpected behavior...


For whatever reason, I am observing that if I use LINQ to find an item from a collection, and later I check to see whether the original collection contains this item, then it always returns false.

3) Using Generic Lists


I was very surprised to see that, sometimes .Contains() does not work properly, I have to use Exists() and then write a delegate to check for the existence.

The same problem manifests when removing an item from the list as well. I have noticed that only the method which takes the delegate for matching actually manages to remove the item from the list.

This is all with .NET 4.0 and VS 2010 SP1.

Comments

Popular posts from this blog

Tutorial: Using Google Cloud Storage from C# and .NET

Late 2008 Macbook only giving 1.5 gb/s speed with 6 gb/s Intel SSD?

The ridiculous interview experience