0
0
CsharpConceptBeginner · 3 min read

Anonymous Method in C#: What It Is and How It Works

An anonymous method in C# is a way to write a method without giving it a name, usually used to create inline code blocks for delegates. It allows you to define a block of code directly where it is needed, making your code shorter and easier to read when you don't need a full method declaration.
⚙️

How It Works

Think of an anonymous method like a quick note you write on a sticky note instead of writing a full letter. Instead of creating a full named method somewhere else in your code, you write the code directly where you need it. This is useful when you want to pass some behavior or action to another part of your program without the overhead of naming and defining a separate method.

In C#, anonymous methods are often used with delegates, which are like pointers to methods. Instead of pointing to a named method, you can point to a block of code written right there. This makes your code more compact and easier to understand in simple cases.

💻

Example

This example shows how to use an anonymous method to print numbers from 1 to 3 using a delegate.

csharp
using System;

class Program
{
    delegate void PrintNumbers();

    static void Main()
    {
        PrintNumbers print = delegate {
            for (int i = 1; i <= 3; i++)
            {
                Console.WriteLine(i);
            }
        };

        print();
    }
}
Output
1 2 3
🎯

When to Use

Use anonymous methods when you need a small piece of code to run in one place and don't want to create a full method for it. They are handy for event handlers, callbacks, or simple delegate assignments where the code is short and used only once.

For example, if you want to respond to a button click in a user interface or process a list with a quick action, anonymous methods let you write that code inline, keeping your program clean and focused.

Key Points

  • Anonymous methods let you write code blocks without naming them.
  • They are mainly used with delegates to pass code inline.
  • They help keep code concise and readable for small tasks.
  • Introduced in C# 2.0, they are a predecessor to lambda expressions.

Key Takeaways

Anonymous methods allow inline code blocks without naming a method.
They are useful for delegates, event handlers, and callbacks.
Use them to keep code concise when a full method is unnecessary.
Anonymous methods were introduced in C# 2.0 before lambdas.
They improve readability by placing code close to where it is used.