.Net application development specialists
asp.net, c#, vb.net, html, javascript, jquery, html, xhtml, css, oop, design patterns, sql server, mvc and much more
contact: admin@paxium.co.uk

Paxium is the company owned by myself, Dave Amour and used for providing IT contract development services including


  • Application development - Desktop, Web, Services - with Classic ASP, Asp.net WebForms, Asp.net MVC, Asp.net Core
  • Html, Css, JavaScript, jQuery, React, C#, SQL Server, Ado.net, Entity Framework, NHibernate, TDD, WebApi, GIT, IIS
  • Database schema design, implementation & ETL activities
  • Website design and hosting including email hosting
  • Training - typically one to one sessions
  • Reverse Engineering and documentation of undocumented systems
  • Code Reviews
  • Performance Tuning
  • Located in Cannock, Staffordshire
Rugeley Chess Club Buying Butler Cuckooland Katmaid Pet Sitting Services Roland Garros 60 60 Golf cement Technical Conformity Goofy MaggieBears Vacc Track Find Your Smart Phone eBate Taylors Poultry Services Lafarge Rebates System Codemasters Grid Game eBate DOFF

Anonymous Methods & Lamda Expressions in C#

With the advent of .NET 2.0 in November 2005 we were given something new called anonymous methods.

Anonymous methods are defined inline and are used when a delegate is normaly used.  Because the method is defined inline it has no method name - hence the name anonymous methods.

Ok this is much easier to see in action so lets look at some code.

Lets first look at some coventional code.  The following is a form with a button on it and shows how we use an event handler in the form of a written method to fire when the button is clicked.  This is all pretty standard and normal.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace AnonymousForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            button1.Click += new EventHandler(button1_Click);
        }
 
        void button1_Click(object sender, EventArgs e)
        {
            MessageBox.Show("Button was clicked");
        }
    }
}


In this code then under the hood the button class will have a delegate which is exposed as an event called Click.  So when the button code raises the Click event it will simply execute all of the event handlers which have been added to the Click event.  An event can have more than one subscriber.  In the above example we have added the button1_Click event handler to the Click event.

With anonymous methods we can achieve exactly the same thing but with less code and more readability as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace AnonymousForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            button1.Click += delegate { MessageBox.Show("Button was clicked"); };
        }
    }
}


Ok so this doesn't mean that we should write everything as anonymous methods.  It just gives us a more concise way of achieveing the same thing and both methods have their ovbvious pros and cons.  It's up to you to use what you think is right for your scenario.  Typically though it will be in the kind of places where the code is very simple, doesn't change and doesn't need to be called directly.

Now you may have noticed that the anonymous method which we wrote didn't adhere to the delegate signature as defined in the Click event.  The delegate should have a signature as follows:

public delegate void EventHandler(object sender, EventArgs e);


So what's happening here?  Well Microsoft designed the compiler so that we don't have to stick to the defined signature if we aren't going to use any of the parameters (eg sender or e).  In this case then we just do what we did in the above example.  If we did want to actually make use of the parameters though we would do so as follows:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace AnonymousForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            button1.Click += delegate(object sender, EventArgs e) { MessageBox.Show(((Button)sender).Name + " button was clicked"); };
        }
    }
}
 


So if we specify a signature then it must match what is expected otherwise we just don't specify one at all.

Ok so that's really all there is to anonymous methods.

In .NET 3.0 we had a new feature called Lamda expressions.  In essense these are basically a more concise way of writing certain kinds of anonymous methods - particularly those which are functional in nature and use the input parameters.  There goal is the same as anonymous methods, they just so in a more concise way.

Lamda expressions make use of an operator which looks like this and is called the lamda operator:

=>
 

This is read out as "goes to" eg

x => x * 2 - reads x goes to x times 2 

The  code example we have been working with would look like this using lamda expressions.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
 
namespace AnonymousForms
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
 
            button1.Click += (object sender, EventArgs e) => MessageBox.Show(((Button)sender).Name);
        }
    }
}


Ok so this isn't a massive amount of conciseness (is that correct english?)  compared with the previous version but when it is used for very simple functional bits of code it is very concise and readable.  It is used particularly extensiveley within Linq.

The above example could also have been written as follows:

button1.Click += (sender, e) => MessageBox.Show(((Button)sender).Name);


What we have done here is not specify the types of the parameters as the compiler can figure them out.  This just aids readability and conciseness.  There are however some instances when the compiler cannot infer the types in which case they can be input as in the first, longer example.  It is normal practice though where possible to omit the parameter types.  Also the brackets surrounding the parameters are optional if there is just 1 parameter.

Let us look at some sample code to see this kind of thing in action.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
 
namespace LinqExamples
{
    public class Program
    {
        static void Main(string[] args)
        {
            Person dave = new Person { FirstName = "Dave", LastName = "Amour", Age = 42 };
            Person fred = new Person { FirstName = "Fred", LastName = "Smith", Age = 22 };
            Person tiff = new Person { FirstName = "Tiff", LastName = "Bloggs", Age = 24 };
            Person kate = new Person { FirstName = "Kate", LastName = "Brown", Age = 33 };
            Person bill = new Person { FirstName = "Bill", LastName = "Green", Age = 38 };
            Person ian = new Person { FirstName = "Ian", LastName = "Smith", Age = 19 };
            Person fiona = new Person { FirstName = "Fiona", LastName = "Williams", Age = 28 };
            Person sonia = new Person { FirstName = "Sonia", LastName = "Johnson", Age = 43 };
 
            Person[] people = new Person[8];
 
            people[0] = dave;
            people[1] = fred;
            people[2] = tiff;
            people[3] = kate;
            people[4] = bill;
            people[5] = ian;
            people[6] = fiona;
            people[7] = sonia;
 
            Console.WriteLine("Max age: " + people.Max(p => p.Age));
            Console.WriteLine("Max surname (ie closest to Z): " + people.Max(p => p.LastName));
 
            Console.Read();
        }
    }
 
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
 
        public override string ToString()
        {
            return FirstName + " " + LastName + " (Age " + Age.ToString() + ")";
        }
    }
}


When we run this code we get the following results.

So what's happening here?

Well the Max method in Linq expects a delegate or lamda expression as an argument.  When the method executes it is doing so against a collection of objects which implements the IEnumerable interface.  Within the code it will use the delegate to figure out which property we want the max calculation to be performed against.

You will find that lamda expressions like this are used a lot in Linq so check out my article on Linq as follows:

http://www.audacs.co.uk/ViewPage.aspx?PageID=529