Freigeben über


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: EricWhite.com/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'
elementFormDefault='qualified'
xmlns:xs='https://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.

Comments

  • Anonymous
    August 19, 2008
    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).

  • Anonymous
    August 19, 2008
    Good point.

  • Anonymous
    October 05, 2010
    I didn't know that too. http://bit.ly/cNYlj0 - another article covers lambdas.