Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

New Features (CS 3.0) - Lambda Expressions

From Wiki

Jump to: navigation, search

Yet another new feature in C# 3.0 is the ability to use Lambda Expressions to execute dynamic code (in the past, I believe you needed to create an assembly on the fly to do so).

I've not yet thought of a good use for this, as it seems more of a functional programming thing, but they are pretty cool.

Basically, if you have a delegate declared (we'll call it del in our example, and assume it takes a DateTime named d as a parameter and returns a string) you can change what it does in your code using the following syntax:

  1. del myDel;
  2. myDel = d => return d.Month.ToString();

The syntax is a little awkward, but its pretty simple when you get used to it.

instanceName = (parameter, list, comma, separated) = { code to execute };

You are not limited to 1 line of code in the area I've called code to execute, as long as you use the { } around it.

Here is a demo of using this feature (used in a console app, again)

First, declare your delegate:

  1. private delegate void dv(String s);

Then, you can use it in the console app's main method.

  1. //we have an instance of the delegate, but what to do with it?
  2. dv varCode;
  3.  
  4. Console.WriteLine("Please enter the magic word!");
  5. string magicWord = Console.ReadLine();
  6.  
  7. Console.WriteLine("Magic word for this show is: " + magicWord +"\nDon't enter it or all hell will break loose!");
  8.  
  9.  
  10. for(int i=0; i<999; i++)
  11. {
  12.     Console.WriteLine("Please enter your name (Cancel or Empty String to exit loop)");
  13.     var str = Console.ReadLine();
  14.  
  15.     if (str == magicWord)
  16.     {
  17.         varCode = s =>
  18.         {
  19.             Console.WriteLine("Uh-Oh, you entered the magic word!");
  20.             Console.WriteLine("Now I have to execute multiple lines of code!");
  21.             var c = s.ToCharArray();
  22.             Array.Sort(c);
  23.             string t = "";
  24.             for (int z = 0; z < c.Length; z++)
  25.             {
  26.                 t = t + c[z].ToString();
  27.             }
  28.             Console.WriteLine("I've organized your entry for you, so hello " + t);
  29.         };
  30.  
  31.     }
  32.     else if (str.Length - str.Replace(" ", "").Length >= 2)
  33.     {
  34.         varCode = s => Console.WriteLine("You appear to have entered more than just your name, but hello anyways " + s);
  35.     }
  36.     else
  37.     {
  38.         varCode = s => Console.WriteLine("Thanks for not entering a whole sentence, " + s);
  39.     }
  40.  
  41.     if (str == String.Empty || str == "Cancel")
  42.         break;
  43.  
  44.     varCode(str);
  45. }
  46.  
  47.  
  48. Console.ReadLine();

And, an example taking >1 parameter

  1. private delegate void ds(String s, DateTime dt);

and the code using it (I hard-coded my name because I'm lazy, feel free to insert you own ;) ):

  1. ds var2;
  2. var2 = (s, dt) =>
  3. {
  4.     var months = new[] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  5.     String monthName = months[dt.Month - 1];
  6.     Console.WriteLine("Hello " + s + ", warm for " + monthName + ", huh??");
  7. };
  8. var2("Alex", DateTime.Now);
  9. Console.ReadLine();


In the six (plus!) months since I originally wrote this, I've been playing a bit with LINQ and found that lambda's can be very useful there. For example, if you wanted to perform an action for each item in your collection where PropX is odd, you could do something like this:

  1. foreach (MyType t in myCollection.Where(t => (t.PropX % 2) == 1))
  2. {
  3.     //do some stuff
  4. }

basically you're defining a function where the input (t) is the item from your collection. This function must also return a boolean value (otherwise how can it be a filter). This is very handy, as you don't have to have a method coded in your class for each type of filter you might want to apply.


Contributed by --AlexCuse 14:22, 24 December 2007 (GMT)

107 Rating: 2.3/5 (8 votes cast)