find and solve || findandsolve.com
Please wait.....

Anonymous Methods And Lambda Expressions In C#

In C#, an anonymous method is a method without a name and can be defined using the delegate keyword and can be assigned to a variable of the delegate type.

In C#, there are two types of anonymous functions as given below.

  • Lambda Expressions
  • Anonymous Methods


C# Lambda Expressions

Lambda expression is an anonymous function that we can use to create delegates. We can use a lambda expression to create local functions that can be passed as an argument. It is also helpful to write LINQ queries.

C# Lambda Expression Syntax

(input-parameters) => expression  


C# Lambda Expressions Example

using System;  

namespace LambdaExpressionsExample
{
    public class Program
    {
        delegate int Square(int num);
        public static void Main(string[] args)
        {
            Square GetSquare = x => x * x;
            int a = GetSquare(5);
            Console.WriteLine("Square: "+a);
        }
    }
}  

Output

Square: 25


C# Anonymous Methods

The anonymous method provides the same functionality as lambda expression, except that it allows us to omit parameter lists. For example:-

using System;  

namespace AnonymousMethods
{
    public class Program
    {
        public delegate void AnonymousFun();
        public static void Main(string[] args)
        {
            AnonymousFun fun = delegate () {
                Console.WriteLine("This is anonymous function");
            };
            fun();
        }
    }
}

Output

This is anonymous function