A Anonymous method is a code block assigned to some delegate.
This concept is introduced in .Net Framework 2.0, before it only named methods could be used with delegates
Scenarios to use:
Some examples of Anonymous functions
This concept is introduced in .Net Framework 2.0, before it only named methods could be used with delegates
Scenarios to use:
- When want to use delegate in same method
- When code is small
- Performance wise anonymous methods are faster than named method
class Program
{
delegate void delAnonymousMethods(int i, int j);
static void Main(string[] args)
{
//anonymous method
delAnonymousMethods delAM = delegate(int i, int j)
{
Console.WriteLine((i + j).ToString());
};
delAM(10, 20);
Console.ReadLine();
}
}
Some examples of Anonymous functions
delegate (int x) { return x + 1; } // Anonymous method expression
delegate { return 1 + 1; } // Parameter list omitted
x => x + 1 // Implicitly typed, expression body
x => { return x + 1; } // Implicitly typed, statement body
(int x) => x + 1 // Explicitly typed, expression body
(int x) => { return x + 1; } // Explicitly typed, statement body
(x, y) => x * y // Multiple parameters
() => Console.WriteLine() // No parameters
async (t1,t2) => await t1 + await t2 // Async
No comments:
Post a Comment