Got more questions? Find advice on: ASP | SQL | Regular Expressions | Windows
in Search
Welcome to XmlAdvice Sign in | Join | Help

Kirk Allen Evans' XML Blog

.NET From a Markup Perspective

Anonymous Methods and Higher-Order Procedures in C#

Steve Maine has a great article on using anonymous methods and higher-order procedures in C#

A point not necessarily highlighted in the article's text but rather through the code examples is that not all problems are solved through inheritance. 

Suppose you have a class that provides methods for working with a certain datastructure.  You might prefer thhe consumer of the class not be required to inherit from your class to effectively use it, and it is not feasible to require the consumer to implement an interface to support your behavior.  A great design pattern involves the use of function pointers, implemented as delegates in .NET.

Consider the example below:  I have an XmlDOMNavigator type that is responsible for loading XML and providing a reference to its root element.  Rather than define the various navigation methods that could possibly occur within the XmlDOMNavigator method, we let the consumer define the implementation of the Traverse method by providing a method that accepts an XmlNode type and returns an XmlNode type.

 

using System;
using System.Xml;

namespace XMLAdvice
{
 class TreeNavigatorSample
 {  
  [STAThread]
  static void Main(string[] args)
  {   
   XmlDOMNavigator nav = new XmlDOMNavigator();
   nav.Load(@"C:\temp\XMLFile1.xml");

   MyNavigator myNav = new MyNavigator();
   
   //Define the move method's type
   XmlDOMNavigator.NavigationMethod MoveChildMethod;

   //Set the type to a new instance
   MoveChildMethod = new XmlDOMNavigator.NavigationMethod(myNav.MoveFirstChild);
   
   XmlNode nodeRef = nav.DocumentElement;

   while(null != nodeRef)
   {
    Console.WriteLine(nodeRef.Name);
    nodeRef = nav.Traverse(nodeRef,MoveChildMethod);     
   }   
  }
 }

 public class MyNavigator
 {
  public XmlNode MoveFirstChild(XmlNode context)
  {
   if(context.HasChildNodes)
   {
    return context.FirstChild;
   }
   else
   {
    return null;
   }
  }
 }

 public class XmlDOMNavigator
 {
  private XmlDocument _doc = new XmlDocument();

  public delegate XmlNode NavigationMethod(XmlNode n);

  public void Load(string path)
  {   
   _doc.Load(path);
  }

  public XmlNode DocumentElement
  {
   get
   {
    return _doc.DocumentElement;
   }
  }

  public XmlNode Traverse(XmlNode context, NavigationMethod customMethod)
  {
   return customMethod(context);
  }
 }
}

Sponsor
Published Thursday, February 12, 2004 11:24 AM by kaevans
Filed under:

Comments

 

kaevans said:

October 25, 2004 7:37 PM
Anonymous comments are disabled

This Blog

Syndication

News

Looking for a place to talk about XML? Tired of the "main feed police" cracking about your interests in football and politics? Sign up for a free web log on XMLAdvice.com.