SyntaxHighlighter Build Test Page
Thoughts from a C# Developer
kennydust (gravatar)

Lambda Expressions

This just in: Lambda Expressions are cool.

Yes, I'm a tad late, given that this language feature has been around for some time (introduced originally in .net 3.0, and packaged in .net 3.5). But to my defense, I have these reasons: (1) There wasn’t a need for it on my end, (2) I was working in a .net 2.0 shop, (3) There were so many feature enhancements that this particular one flew under the radar.

Fast forward to today, I've written my first lambda expression and wish to share it.

So what are lambda expressions? In my own words, they are just another way of writing code statements; a shorthand way of encapsulating logic. They can be "expressions" and "statements", and can be assigned to a delegate type. A lambda expression contains a "lambda operator," =>, with the left side of the expression responsible for handling input and the right side containing logic:

  //assuming x equates to a value of 10
  x => x + x;

  (10) => (10) + (10) //equals 20

Below are a few examples I've put together, they are pretty simplified, but it demonstrates how powerful lambda expressions can be. The challenge? Given some DateTime value, perform a comparison to see whether or not this value has exceeded 24 hours.

To start, here’s the original snippet that was coded up.

DateTime expiredTime = DateTime.Parse("1/1/2009"); 
DateTime adjustedTime = DateTime.Now.AddHours(-24);

//original statement 
int comparsionResult = DateTime.Compare(adjustedTime, expiredTime); 
bool isExpired = (comparsionResult > 0);

It's pretty straight forward and it does the job. But we want lambda expressions. Here's an example of that, with an expression that's assigned to a delegate type that expects one input:

delegate bool del(DateTime t); 
static void Main(string[] args)
{
   DateTime expiredTime = DateTime.Parse("1/1/2009"); 
   DateTime adjustedTime = DateTime.Now.AddHours(-24);

   del comparisonDel = x => (DateTime.Compare(adjustedTime, x) > 0);
   bool isExpired = comparisonDel(expiredTime);
}

The second example demostrates wrapping a lambda expression in a Func<> generic delegate.

DateTime expiredTime = DateTime.Parse("1/1/2009"); 
DateTime adjustedTime = DateTime.Now.AddHours(-24);

 //Lambda Expression Wrapped in a Func<>
Func ComparisonCheck = x => (DateTime.Compare(adjustedTime, x) > 0);
bool isExpired = ComparisonCheck(expiredTime);

2 Comments

Your Information
Mrs. Gravatar (gravatar)

<-- It's a gravatar

your comment