Monthly Archives: February 2013

Flavors of C# anonymous delegages

using System;

namespace ConsoleApplication1
{
    class Program
    {
        delegate void void_int_delegate(int x);
        delegate int int_int_delegate(int x);
        static void Main(string[] args)
        {
            //Create a delegate that writes its argument +1 using anonymous delegate syntax
            void_int_delegate d = delegate(int i) { Console.WriteLine(i + 1); };
            d(1);
            //overwrite the delegate with an equavalent one using the lamda syntax
            d=(int j)=>Console.WriteLine(j+1);
            d(1);

            //The equivalent of the previous versions but that return values
            int_int_delegate e = delegate(int i) { Console.WriteLine(i + 1); return i + 1; };
            Console.WriteLine(e(2));
            e = (int j) => { Console.WriteLine(j + 1); return j + 1; };
            Console.WriteLine(e(2));

            Console.ReadKey();
        }
    }
}

P.S. There's another, very practical, version that I've run into lately that avoids having to declare the delegate methods before-hand:
Func<XmlDocument,string,string> extractText = (xmldocument, xpath) =>
 {
  var n=xmldocument.SelectSingleNode(xpath);
  if(n==null) return "";
  return n.InnerText;
 };
string file_name = extractText(xdoc, String.Format("//function[name='{0}']/dll/file", FunctionName));
string class_name = extractText(xdoc, String.Format("//function[name='{0}']/dll/class", FunctionName));

Financial Book

I put together this guide to personal finance: “Thinking about Money” but I have been very shy about releasing it.  It will be here until I change my mind.  The odd PDF page size is to make it easier to read on e-readers.