Willy's Reflections

| Willy-Peter Schaub | Visual Studio ALM Rangers | In search of IT simplicity, quality and tranquility |

Getting to grips with C# Lambda … a random vacation thread that drove me crazy

Getting to grips with C# Lambda … a random vacation thread that drove me crazy

  • Comments 1

Last week I was completely disconnected from the digital world and unfortunately a thread fired while I was sitting at the Osoyoos lake staring at this (picture right):
DSCN4051

The thread started pondering over Lambda Expressions, which I have not used for months. As you can imagine it drove me crazy, because while I was trying to remember the details around the lambda expressions, I had no means to check the old community quick reference posters on S.A. Architect (click on extract below to zoom over to poster):

SAA_Lamda

So, to suspend the thread I have decided to summarize what I believe is important in terms of Lambda Expressions.

What are they … MSDN version?

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.
http://msdn.microsoft.com/en-us/library/bb397687.aspx

What are they?

A placeholder for a nameless (anonymous) delegate instance.

Instead of writing this …

// Create a delegate.
delegate void Del(int x);

// Instantiate the delegate using an anonymous method.
Del d = delegate(int k) { /* ...code using parameter k... */ };

You can write this …

// Create a delegate.
delegate void Del(int x);

// Instantiate the delegate using a lambda expression.
Del d = (k) => { /* ...code using parameter k... */ };

A lambda expression has the basic (input parameters) => expression syntax.

Simple examples pulled primarily from MSDN and used in the tour solution:

  1: // --------------------------------------------------------------------------------------------------------------------
  2: // <copyright company="Microsoft Corporation" file="Program.cs">
  3: //   Copyright Microsoft Corporation. All Rights Reserved. This code released under the terms of the Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) This is sample code only, do not use in production environments.
  4: // </copyright>
  5: // <summary>
  6: //   Part of Visual Studio ALM Rangers - Willy's Cave Dwelling Journals
  7: // </summary>
  8: // --------------------------------------------------------------------------------------------------------------------
  9: 
 10: namespace _7_Lambda
 11: {
 12:     using System;
 13:     using System.Collections.Generic;
 14:     using System.Linq;
 15:     using System.Text;
 16:     using System.Threading.Tasks;
 17: 
 18:     /// <summary>
 19:     /// Lambda test environment
 20:     /// </summary>
 21:     public class Program
 22:     {
 23:         /// <summary>
 24:         /// Demo delegate.
 25:         /// </summary>
 26:         /// <param name="i">demo integer.</param>
 27:         /// <returns>Integer demo result.</returns>
 28:         public delegate int DelDemo(int i);
 29: 
 30:         /// <summary>
 31:         /// Demo Main.
 32:         /// </summary>
 33:         /// <param name="args">In this case no arguments.</param>
 34:         public static void Main(string[] args)
 35:         {
 36:             // Squaring Lambda
 37:             DelDemo demoDel = x => x * x;
 38:             Console.WriteLine("x => x * x ... x=13 ... result = " + demoDel(13));
 39: 
 40:             // Odd numbers Lambda
 41:             int[] numbers = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 42:             int oddNumbers = numbers.Count(n => n % 2 == 1);
 43:             Console.WriteLine("n => n % 2 == 1 ... n = 0...10 ... result = " + oddNumbers.ToString());
 44: 
 45:             // Less than five
 46:             var greaterFive = numbers.TakeWhile(n => n < 5);
 47:             Console.WriteLine("n => n > 5 ... n = 0...10 ... result = " + greaterFive.Count().ToString());
 48: 
 49:             // Fruits
 50:             // public static IEnumerable<TSource> TakeWhile<TSource>(
 51:             //                                                        this IEnumerable<TSource> source,
 52:             //                                                        Func<TSource, bool> predicate
 53:             //                                                      )
 54:             string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };
 55:             IEnumerable<string> query = fruits.TakeWhile(fruit => string.Compare("orange", fruit, true) != 0);
 56:             foreach (string fruit in query)
 57:             {
 58:                 Console.WriteLine(fruit);
 59:             }
 60: 
 61:             // First number > 5
 62:             int greaterNumbers = numbers.Count(n => n > 5);
 63:             Console.WriteLine("n => n > 5 ... n = 0...10 ... result = " + greaterNumbers.ToString());
 64: 
 65:             Console.ReadKey();
 66:         }
 67:     }
 68: }
 69: 

Why are they such a brain twister? … my personal view!

For those (like I) who have never grown accustomed to the syntax and value of anonymous methods, the syntax appears cryptic, resulting in pauses and minor brain resets while reading source code that has settlements of lambda expressions. While they are brain twisters and cryptic, they are becoming common citizens in source code and it is necessary for all of us to embrace them as friends :)

They can, however, make code harder to read and you should ensure that you do not start over using them just ‘because’.

When are they useful?

If you (especially you Robert) have any additional feedback, corrections to the above or ideas on how to demystify this feature, then please add comments Smile

  • great!

Page 1 of 1 (1 items)
Leave a Comment
  • Please add 6 and 5 and type the answer here:
  • Post