Thursday, July 9, 2015

C# Anonymous Functions

Intro

Anonymous Functions: Things that activist hacker group does when they go into the potty room. Darn, I keep forgetting this is a programming blog! OK in this case an Anonymous Function is an "inline statement or expression that can be used wherever a delegate type is expected." (1). In layman's terms, rather than supplying a fully-defined function to a delegate, you can create an anonymous function within your normal code and use that. It's hard to explain, so let's see it in action.



Code Samples in VS2013, .Net 4.5.

Simple Use Case



using System;

namespace BlogAnonymousFunction
{
    public class Thingy
    {
        public string DoAThing(int val1, int val2, Func preProcessor = null)
        {
            int val3 = -1;
            if (preProcessor != null)
                val3 = preProcessor(val1, val2);
            return String.Format("val1:{0}, val2:{1}, val3: {2}", val1, val2, val3);
        }
    }
}


using System;

namespace BlogAnonymousFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            var thingy = new Thingy();
            var result = thingy.DoAThing(24, 42, null);
            Console.WriteLine(result);
            result = thingy.DoAThing(24, 42, new Func((val1, val2) => val1 + val2));
            Console.WriteLine(result);
            Console.ReadKey();
        }
    }
}



A simple example to be certain. Our class Thingy has a single method DoAThing that accepts a function as a parameter. If the user passes in a value for this nullable function we will call it and set it to our 3rd value.

In the Main method we call DoAThing twice. First we call it once passing in a null function parameter. In the second call we pass in an anonymous function that adds the first and 2nd parameter, returning the result. You can see the results of our two function calls in the output window screenshot below.


Cool huh? Simple too, but it does take a few repetitions to get used to the odd syntax. Enjoy!

What's Next?

You can also do generic methods (no return type), you can create variables that reference a generic function/method, and more! Search on teh webs, you'll find plenty.

Resources

(1) Anonymous Functions
The Generic Func Delegates

No comments:

Post a Comment