Category: DotNetGotcha

Awaiting for that Button click

Why wait when we can await? I believe that most of C# developers know about the new language features for asynchronous programming with async and await keywords but how many of us are really exploiting them to full extent? Recently i was watching the excellent C# Language Internals course on PluralSight.com by Bart De Smet and came across very cool idea of using Await to wait for Button to be clicked – which pushed me to write this post and share it with everyone. By implementing a custom awaiter for Button (via extension methods) and hooking up to the Click handler…

Dot Net Gotcha #2 – Loop variables and Closures

This one is my favorite. Can you guess the output of this simple console application: One would expect to see numbers from 0 to 9 but here is the actual output of the app: OK that’s strange right? It turns out its like that by design. What you have there is a Closure over the loop variable. And closures in C# are done around variables and not around specific values of those variables – so that means that lambda expression gets to use the actual reference to the closed variable. Let me explain in little bit more detail: In first loop…

Dot Net Gotcha #1 – List versus Collection constructor

Don’t Google it! Do you know (without Googling it) what will this console application display when executed? If you try to think logically, you expect that both List and Collection will contain numbers from 1 to 6 when they are displayed, right? Wrong, otherwise this would not be a proper gotcha 😉 Here is the actual output of the application (surprise, surprise): Do you know why? Answer is actually very simple. If you check the MSDN documentation for Collection constructor that accepts generic IList you will see this text: Initializes a new instance of the Collection class as a wrapper for…