10X Sale
kh logo
All Courses
  1. Tutorials
  2. Programming Tutorials

Anonymous Methods in C#

Updated on Sep 3, 2025
 
45,998 Views

Anonymous methods are unnamed methods in a code that can be defined using the delegate keyword. They only require a body and not a name or a return type. Anonymous methods allow users to write inline codes rather than explicit methods. Their behaviour is similar to normal methods.

Salient Points of Anonymous Methods

Some of the salient points of Anonymous methods are as follows:

  1. Anonymous methods are defined using the delegate keyword.
  2. Anonymous methods can be used in event handling.
  3. Any unsafe codes cannot be accessed inside anonymous methods.
  4. Variables declared outside the anonymous methods can be accessed inside them.
  5. Variables declared inside the anonymous methods cannot be accessed outside them.
  6. Anonymous methods can be passed as parameters.

A program that demonstrates Anonymous methods is given as follows:

using System;
namespace AnonymousMethodDemo
{
  class Example {
     public delegate void sum(int x, int y);
     static void Main(string[] args)
     {
        sum s = delegate(int x, int y)
        {
          Console.WriteLine("Inside Anonymous method");
          Console.WriteLine("Sum = {0}",x + y);
        };
        s(7, 12);
     }
  }
}

Source Code: Program that demonstrates Anonymous methods in C#

The output of the above program is as follows:

Inside Anonymous method
Sum = 19

Limitations of Anonymous Methods

Some of the limitations of Anonymous methods are given as follows:

  1. Any unsafe codes cannot be accessed inside anonymous methods.
  2. There cannot be jump statements such as goto, break or continue inside anonymous methods.
  3. Anonymous methods cannot be used on the left side of the is operator.
+91

By Signing up, you agree to ourTerms & Conditionsand ourPrivacy and Policy

Get your free handbook for CSM!!
Recommended Courses