Tuesday 30 June 2015

Anonymous functions

Anonymous functions are functions that you create inline as needed, for example lets say you have a delegate that formats a name. You could assign a defend function to it by declaring the function with a name and then adding that function to the invocation list of the delegate.

namespace pav.anonymousFunctions;

class Program
{
    delegate string FormatNameDelegate(string LastName, bool Male, bool Doc);

    static string FormatNameFn(string LastName, bool Male, bool Doc = false)
    {
        return Doc ? $"Dr. {LastName}" : String.Concat(Male ? "Mr." : "Ms.", LastName);
    }

    static void Main(string[] args)
    {
        FormatNameDelegate declaredFn = FormatNameFn;

        Console.WriteLine(declaredFn.Invoke("Jones", true, true));

        declaredFn -= FormatNameFn;
    }
}


above we Defined the FromatNameDelegate,  created a function that formats the name, then in the main method we assign our function to our delegate reference, and finally call it. Perfectly valid code, especially if we want to later remove the delegate.

however if we have no need of removing the delegate, then we can simply reference an anonymous function to our FormatName Delegate.


namespace pav.anonymousFunctions;
class Program
{
    delegate string FormatNameDelegate(string LastName, bool Male, bool Doc);

    static void Main(string[] args)
    {
        FormatNameDelegate declaredFn = (LastName, Male,  Doc) =>
            Doc ? $"Dr. {LastName}" : String.Concat(Male ? "Mr." : "Ms.", LastName);

        Console.WriteLine(declaredFn.Invoke("Jones", true, true));
    }
}


because in the anonymous version, there is no defined FormatNameFn, there is no way to remove it from the invocation list of the declaredFn delegate.