Thursday 10 December 2015

The Anonymous from C#

Going anonymous

Prior to .NET 2.0, the only way to declare a delegate was to use named methods. While this was a way but it was not that very fluent. The programmer has to create a new method that conforms to the signature of the delegate and then pass it to the delegate. This is fine when you write small programs but as the project grows, it begins to cramp up the maintenance process. If a fellow programmer has to fix a bug then first a search for the method in the source code has to be done following the fix up process. It is definitely a time consuming process.


Enter anonymous 

.NET 2.0 introduced the concept of the anonymous method which powers the developer to define the method inline to the call.

 public delegate int MathOperationDelegate(int x, int y);
    class Program
    {
        static void Main(string[] args)
        {
            MathOperationDelegate operationDelegate = null;
 
 
            //No need to create a seperate method
            operationDelegate += delegate(int x, int y)
            {
                return x + y;
            };
 
            operationDelegate += delegate(int x, int y)
            {
                return x - y;
            };
            operationDelegate += delegate(int x, int y)
            {
                return x * y;
            };
            operationDelegate += delegate(int x, int y)
            {
                return x / y;
            };
 
 
            //Prior to .NET 2
            //Methods have to be explicitely created, prior to the Invoke
            operationDelegate += OnAddMathOperationDelegate;
 
            operationDelegate += OnMulMathOperationAction;
 
            operationDelegate += OnDivMathOperationAction;
 
            operationDelegate += delegate(int x, int y)
            {
                return x / y;
            };
 
 
           var result = operationDelegate(12, 12);
           Console.WriteLine(  result );
        }
 
        private static int OnDivMathOperationAction(int x, int y)
        {
            return x*y;
        }
 
        private static int OnMulMathOperationAction(int x, int y)
        {
            return x - y;
        }
 
        private static int OnAddMathOperationDelegate(int x, int y)
        {
            return x + y;
        }
 
    }


The above program shows both named and anonymous method.
From the first observation, anonymous methods are easy to create and debug. Maintenace is much simpler. 

By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method. For example, specifying a code block instead of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead.


la la al

No comments:

Post a Comment