Skip to main content
Anonymous Methods

Anonymous Methods in C# with example

First of all, as the name suggests, an anonymous method is a method without a name. Anonymous methods in C# can be defined using the delegate keyword and can be assigned to a variable of the delegate type.

Anonymous Methods in C# with example #csharp #anonymousmethods #dotnet Click To Tweet

C# Anonymous Methods

Probably anonymous methods were introduced in C# 2.0 version. To know more about C# features with respect to its versions, navigate to the below post.

List of C# features version by version

Example:

public delegate void Print(string value);

static void Main(string[] args)
{
Print print = delegate(string val) {
Console.WriteLine("Inside Anonymous method. Value: {0}", val);
};

print("DotnetCrunch");
}

Output:

Inside Anonymous method. Value: DotnetCrunch

Few more examples:

Anonymous method as an event handler


saveRecord.Click += delegate(Object o, EventArgs e)
                    { 
                        MessageBox.Show("Record saved!"); 
                    };

Anonymous method as method parameter

public delegate void Interval(int value);

class Program
{
    public static void IntervalHelper(Interval interval,int val)
    { 
        val += 10;
        interval(val);
    }

    static void Main(string[] args)
    {
        IntervalHelper(delegate(int val) 
        { 
             Console.WriteLine("Anonymous method: {0}", val); 
         }, 10);
    }
}

Output:

Anonymous method: 20

Features:

  1. Anonymous methods can be used as event handlers.
  2. They can access variables defined in an outer function.
  3. It can also be passed to a method that accepts the delegate as a parameter.

Limitations:

  1. It cannot contain jump statement like goto, break or continue.
  2. It cannot access ref or out parameter of an outer method.
  3. Anonymous methods cannot have or access unsafe code.
  4. We cannot use anonymous methods on the left side of the is operator.

In conclusion to this post, we hope that you like this short and simple explanation for anonymous methods in C#.

What do you think?

Dear Readers,
If you have any questions or suggestions please feel free to email us or put your thoughts as comments below. We would love to hear from you. If you found this post or article useful then please share along with your friends and help them to learn.

Happy Coding!

Was this article worth reading? Share it with fellow developers too.

DotNetCrunch

DotNetCrunch is a popular blog for latest Microsoft® technologies which is aimed for beginners and intermediate level professionals.