Anonymous Methods in C#

 Why do we need Anonymous Methods in C#?

In our Delegates in C# article, we discussed how to bind a delegate with a method. To bind a delegate with a method, first, we need to create an instance of the delegate and when we create the instance of the delegate, we need to pass the method name as a parameter to the delegate constructor, and it is the function the delegate will point to and when we invoke the delegate, this function which is pointed by the delegate is going to be executed. It is also possible that the delegates might be pointed to multiple functions and in that case, when we invoke the delegate instance, then all the functions which are pointed by the delegate are going to be executed.

Example to Understand Delegate in C#:

Before understanding the anonymous method, let us first see how we can use a delegate to execute the method. Why because to understand the Anonymous method, it is important to understand delegate because anonymous methods are used delegate. The following example shows how to declare a delegate, how to create an instance of a delegate, and how to invoke the delegate.

using System;
namespace DelegateDemo
{
    public class AnonymousMethods
    {
        public delegate string GreetingsDelegate(string name);
        public static string Greetings(string name)
        {
            return "Hello @" + name + " Welcome to Dotnet Tutorials";
        }

        static void Main(string[] args)
        {
            GreetingsDelegate gd = new GreetingsDelegate(AnonymousMethods.Greetings);
            string GreetingsMessage = gd.Invoke("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the following output.

Example to Understand Delegate in C#

In the above example,

  1. We create one delegate (GreetingsDelegate)
  2. Then we instantiate the delegate, while we are instantiating the delegate, we are passing the Method name (Greetings) as a parameter to the constructor of the delegate
  3. Finally, we invoke the delegate

As of now, this is the approach we are following to bind a method to a custom delegate and execute it. An anonymous method in C# is also related to a delegate. Without binding a named block (function or method) to a delegate, we can also bind a code block (unnamed code block) to a delegate which is nothing but an anonymous method in C#.

Example to Understand Anonymous Methods in C#

The following example is the same as the previous example except here instead of binding the delegated with a named block (method or function), we are binding the delegate with an anonymous method (you can also unnamed code block).

using System;
namespace DelegateDemo
{
    public class AnonymousMethods
    {
        public delegate string GreetingsDelegate(string name);

        static void Main(string[] args)
        {
            GreetingsDelegate gd = delegate (string name)
            {
                return "Hello @" + name + " Welcome to Dotnet Tutorials";
            };
            string GreetingsMessage = gd.Invoke("Pranaya");
            Console.WriteLine(GreetingsMessage);
            Console.ReadKey();
        }
    }
}

When you run the above code, you will get the same output as the previous example as shown in the below image.

Example to Understand Anonymous Methods in C#

In the above example, the following code is an example of an Anonymous method. In this case, as you can see, instead of a method, we are binding the delegate to an unnamed code block which is also called an anonymous method and in C#, the anonymous methods are created by using the delegate keyword and if the anonymous method requires any input parameter, then you can pass the parameter within the parenthesis. Here, you can see, we are passing the string name parameter.

Example to Understand Anonymous Methods in C#

Note: As you can see, the above code block is without a name and it contains only the method body and the method is defined using the delegate keyword. We do not require writing any access modifiers like public, private, protected, etc. We also do not require writing any return type like the void, int, double, etc. The point that you need to remember is anonymous methods are always going to be void type and moreover you cannot reuse the anonymous method. Where you define the anonymous method, at that place only it is going to be used.

Comments

Popular posts from this blog

C# | Association, Aggregation and Composition

Throw vs Throw ex in C#

C# Extension Method