August, 2008

  • Eric White's Blog

    Use a Lambda Expression for an Event Handler

    • 3 Comments

    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='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.

Page 4 of 11 (11 items) «23456»
Page 2 of 2 (11 items) 12