- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What are anonymous methods in C#?
Anonymous methods are the methods without a name. These methods provide a technique to pass a code block as a delegate parameter.
Anonymous methods are declared with the creation of the delegate instance, with a delegate keyword.
Example
using System; delegate void Demo(int n); namespace DelegateAppl { class TestDelegate { static int num = 50; public static void AddNum(int p) { num += p; Console.WriteLine("Named Method: {0}", num); } public static void MultNum(int q) { num *= q; Console.WriteLine("Named Method: {0}", num); } public static int getNum() { return num; } static void Main(string[] args) { //create delegate instances using anonymous method Demo d = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; //calling the delegate using the anonymous method d(100); //instantiating the delegate using the named methods d = new Demo(AddNum); //calling the delegate using the named methods d(5); //instantiating the delegate using another named methods d = new Demo(MultNum); //calling the delegate using the named methods d(2); Console.ReadKey(); } } }
Output
Anonymous Method: 100 Named Method: 55 Named Method: 110
Above the following is our anonymous method.
Demo d = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); };
Advertisements