Welcome to MSDN Blogs Sign in | Join | Help
Use a Lambda Expression for an Event Handler

[Blog Map] 

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:

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'

                       elementFormDefault='qualified'

                       xmlns:xs='http://www.w3.org/2001/XMLSchema'>

              <xs:element name='Snippet'>

                <xs:complexType>

                  <xs:attribute name='Id'

                                type='xs:unsignedByte' use='required' />

                </xs:complexType>

              </xs:element>

            </xs:schema>";

        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");

        else

            Console.WriteLine(errors);

    }

}

 

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

Posted: Tuesday, August 19, 2008 1:25 PM by EricWhite

Comments

int19h said:

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).

# August 19, 2008 11:36 AM

EricWhite said:

Good point.

# August 19, 2008 5:24 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 

  
Enter Code Here: Required

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Page view tracker