Posted by: Mark Wilkinson | August 5, 2009

Embracing Lambda Expressions

I’ve put off using a lot (or really most of the features) in C# 3. Lambdas being one of them.

I originally started programming in .NET 2.0 and C# 2. Although the way I originally learned how to use delegates and invoke was from C# 1.

Dan Vanderbloom’s blog has the best example of this transition.

Here was my progression and the way I inovked a delegate to post back to a control on another thread.

First, we declare the delegate, then in a method you need to create an instance of the delegate, and invoke it:

untitled

You test if this.invokeRequired(), which will be yes if you’re on a different thread than what the control you’re invoking is on.

If this is the case you’ll go back into the function through the delegate method who’s target is the same method (a shortcut really, most have this outside the target method).

Not really all that complicated, but I had to make a target function and delegate for each type of input parameter.

Now with Lambdas, it’s this simple (to do the same as above):

You do need this function inside the same namespace of your class (not required within the class though).

untitled2

with this function you can now use this lambda expression:

invokeWithLambda

pretty Rad. ;)


Leave a response

Your response:

Categories