English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
As the name implies, anonymous methods are methods without a name. You can define anonymous methods in C# using the delegate (delegate) keyword and assign them to delegate (delegate) type variables.
In an anonymous method, you do not need to specify the return type, which is inferred from the return statement within the method body.
public delegate void Print(int value); static void Main(string[] args) { Print print = delegate(int val) { Console.WriteLine("Inside the anonymous method. Value: {0}", val); }; print(100); }
Inside the anonymous method. Value:100
Anonymous methods can access variables defined in external functions.
public delegate void Print(int value); static void Main(string[] args) { int i = 10; Print prnt = delegate(int val) { val += i; Console.WriteLine("Anonymous method: {0}", val); }; prnt(100); }
Anonymous method:110
Anonymous methods can also be passed to methods that accept delegates as parameters.
In the following example, PrintHelperMethod() uses the first parameter of the Print delegate:
public delegate void Print(int value); class Program { public static void PrintHelperMethod(Print printDel, int val) { val += 10; printDel(val); } static void Main(string[] args) { PrintHelperMethod(delegate(int val) { Console.WriteLine("Anonymous method: {0}", val); }, 100); } }
Anonymous method:110
saveButton.Click += delegate(Object o, EventArgs e) { System.Windows.Forms.MessageBox.Show("Save Successfully!"); };
C#3Version .0 introduced lambda expressions, which work like anonymous methods.
It cannot contain jump statements such as goto, break, or continue.
It cannot access external method's ref or out parameters.
It cannot own or access unmanaged code.
Cannot be used on the left side of the is operator.
Anonymous methods can be defined using the delegate keyword
Anonymous methods must be assigned to delegates.
Anonymous methods can access external variables or functions.
Anonymous methods can be passed as parameters.
Anonymous methods can be used as event handlers.