Use a Lambda Expression for an Event Handler

You can use lambda expressions to write an event handler, even for classes that predate C# 3.0 and the latest version of the framework.  This can shorten your code, and make it easier to read.  For example, the code to validate an XML tree using an XSD schema takes an event handler because it may return multiple errors or warnings for a single validation pass.  An easy way to write this code is as follows:

This blog is inactive.
New blog:

Blog TOC

using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Schema;
class Program
    static void Main(string[] args)
        string xsdMarkup =
          @”<xs:schema attributeFormDefault=’unqualified’
              <xs:element name=’Snippet’>
                  <xs:attribute name=’Id’
                                type=’xs:unsignedByte’ use=’required’ />
        XmlSchemaSet schemas = new XmlSchemaSet();
        schemas.Add(“”, XmlReader.Create(new StringReader(xsdMarkup)));
        XDocument snippet = XDocument.Parse(“<Snippet Idx=’0001’/>”);
        string errors = null;
        snippet.Validate(schemas, (o, e) => errors += e.Message + Environment.NewLine);
        if (errors == null)
            Console.WriteLine(“Passed Validation”);

I used this same approach in Running an Executable and Collecting the Output.

Comments (3)

  1. int19h says:

    In addition to that, I’ve found that a lot of people do not know that you can use all the new language features even in VS2008 projects that target .NET 2.0 or 3.0 (and not 3.5).

  2. EricWhite says:

    Good point.

  3. Lambda Expressions says:

    I didn't know that too. – another article covers lambdas.