Skip to main content

Posts

Deferred execution in C#

A lot of times, fellow developers ask me about yield return keyword and what this keyword is for. This keyword allows us to iterate over enumerable collections in a more efficient way. Basically what does is tells the compiler do not execute this code unless is strictly necessary (for this reason it’s also called lazy evaluation). I wrote a little sample that shows the keyword in action. The purpose of this code is to convert a DataTable into a Collection of objects. Maybe the algorithm is not the best way to accomplish the job but clearly shows how yield return works. To see the advantages of lazy evaluation we first should take look at how the code will work if we don’t use it. Here I convert a DataTable that contains four rows into a collection of objects and take the first element from the result. This version of convert works eagerly. And the result is: As we can see this in the output window, this version of the convert method walks thru the whole rows collection converting ea...

How to copy event handlers from one control to another

Today at work, one of my partners in crime were working on a crazy customer requirement and ask me if I think that would be possible to copy event handlers from one control to another at run time and keeps things working correctly. I said yes, I think it’s possible and must be easy too, let’s take a look… After a couple of minutes, we figure out that the Control class doesn´t expose any public method or property to get access to the collection of delegates attached to the control’s events. I did a fair amount of web research and found a lot of partial solutions but none that fit our needs. So I decide to roll my own solution, post it, and may help some who is facing the very same problem. Normally when we are working with events, we hook them up with handlers, writing a piece of code like this: textBox1.TextChanged += (s, e) =>  MessageBox .Show( "Hi there from handler 1" );   It’s also common to attach more th...