Search⌘ K

Anonymous Methods

Create methods without giving them names.

Introduction

Anonymous methods are nameless methods. They’re often used to instantiate delegates. The syntax for creating an anonymous method is as follows:

delegate(parameters)
{
	// Method body
}

Let’s see an example:

C#
using System;
namespace AnonymousMethods
{
delegate void MessagePrinter();
class Program
{
static void Main(string[] args)
{
// This delegate will have the reference
// of the anonymous method
MessagePrinter printer = delegate()
{
Console.WriteLine("Hello World!");
};
printer();
}
}
}

Use anonymous

...