An anonymous method is a method which doesn’t contain any name which is introduced in C# 2.0. It is useful when the user wants to create an inline method and also wants to pass parameter in the anonymous method like other methods. An Anonymous method is defined using the delegate keyword and the user can assign this method to a variable of the delegate type.
Syntax:
delegate(parameter_list){
// Code..
};
Example :
using System;
class GFG {
public delegate void petanim( string pet);
static public void Main()
{
petanim p = delegate ( string mypet)
{
Console.WriteLine( "My favorite pet is: {0}" ,
mypet);
};
p( "Dog" );
}
}
|
Output:
My favorite pet is: Dog
Important Points:
- This method is also known as inline delegate.
- Using this method you can create a delegate object without writing separate methods.
- This method can access variable present in the outer method. Such type of variables is known as Outer variables. As shown in the below example fav is the outer variable.
Example:
using System;
class GFG {
public delegate void petanim( string pet);
static public void Main()
{
string fav = "Rabbit" ;
petanim p = delegate ( string mypet)
{
Console.WriteLine( "My favorite pet is {0}." ,
mypet);
Console.WriteLine( "And I like {0} also." , fav);
};
p( "Dog" );
}
}
|
Output:
My favorite pet is Dog.
And I like Rabbit also.
- You can pass this method to another method which accepts delegate as a parameter. As shown in the below example:
Example :
using System;
public delegate void Show( string x);
class GFG {
public static void identity(Show mypet,
string color)
{
color = " Black" + color;
mypet(color);
}
static public void Main()
{
identity( delegate ( string color) {
Console.WriteLine( "The color" +
" of my dog is {0}" , color); },
"White" );
}
}
|
Output:
The color of my dog is BlackWhite
- In anonymous methods, you are allowed to remove parameter-list, which means you can convert an anonymous method into a delegate.
- The anonymous-method-block means the scope of the parameters in the anonymous method.
- An anonymous method does not contain jump statements like goto, break, or continue.
- An anonymous method does not access unsafe code.
- An anonymous method does not access in, ref, and out parameter of the outer scope.
- You can not use an anonymous method to the left side of the is operator.
- You can also use an anonymous method as an event handler.
Example:
MyButton.Click += delegate (Object obj, EventArgs ev)
{
System.Windows.Forms.MessageBox.Show( "Complete without error...!!" );
}
|
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
11 Feb, 2019
Like Article
Save Article