How to use anonymous and Lambda expression in .net

In this post I will discuss how to use anonymous and lambda expression in .net.

Imagine we have a simple example in c# that simply add two numbers.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

class Program
{
    public delegate int Fn(int a, int b);
    static void Main(string[] args)
    {
        Fn add = new Fn(Add);
        Console.WriteLine(add(1, 2));
    }
    public static int Add(int a, int b)
    {
        return (a + b);
    }
} 

Let’s refactor the delegate instance version of the code to use an anonymous method.

What is the anonymous method?

Anonymous methods are a new language feature in C# 2.0. Anonymous methods allow us to define a code block where a delegate object is acceptable.

Let’s convert the above code using anonymous code.

Remove the following method from the delegate instance version

public static int Add(int a, int b)
{
	return (a + b);
}

And replace the following code with

Fn add = new Fn(Add);

With this one.

Fn add = delegate(int a,int b)
            { return (a+b);
            }; 

Now we can write code as shown below to use the above-defined class using the anonymous method as follows:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


    class Program
    {
        public delegate int Fn(int a, int b);
        static void Main(string[] args)
        {
1.    Fn add = delegate(int a, int b)
2.    {
3.    return (a + b);
4.    };

            Console.WriteLine(add(1, 2));
        }

    }


Let’s go further and refactor our code using Lambda Expression.

What is a lambda expression?

Lambda expression is inline methods that are part of the Linq technology and converted to delegates or an expression tree at compile time. Its use => operator to separate method. Meaning of => operator is goes to i.e. if you have a c# statement x=>x+y then you read this statement as x goes to x+y.
Go to line 1 and remove the delegate keyword.

   Fn add = (int a, int b)
            {
                return (a + b);
           };

And place lambda sign => after method signature.

   Fn add = (int a, int b)=>
            {
                return (a + b);
};

So this final lambda expression version code looks something like this.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


    class Program
    {
        public delegate int Fn(int a, int b);
        static void Main(string[] args)
        {
            Fn add = (int a, int b) =>
            {
                return (a + b);
            };

            Console.WriteLine(add(1, 2));
        }

    }

I have summarized the above discussion into the following image.



Post a Comment

Please do not post any spam link in the comment box😊

Previous Post Next Post

Blog ads

CodeGuru