
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Anonymous Methods in C#
Pass a code block as a delegate parameter in C#, using the Anonymous methods in C#. Anonymous methods are the methods without a name, just the body.
This is how you can declare Anonymous methods −
delegate void DemoMethod(int n); ... DemoMethod dm = delegate(int a) { Console.WriteLine("Our Anonymous Method: {0}", a); };
As shown above, the following is the body of the anonymous method −
Console.WriteLine("Our Anonymous Method: {0}", a);
Example
You can try to run the following code to implement Anonymous methods in C# −
using System; delegate void Demo(int n); namespace MyDelegate { class TestDelegate { static int num = 10; public static void DisplayAdd(int p) { num += p; Console.WriteLine("Named Method: {0}", num); } public static void DisplayMult(int q) { num *= q; Console.WriteLine("Named Method: {0}", num); } public static int getNum() { return num; } static void Main(string[] args) { Demo dm = delegate(int x) { Console.WriteLine("Anonymous Method: {0}", x); }; //calling the delegate using the anonymous method dm(15); //instantiating the delegate using the named methods dm = new Demo(DisplayAdd); //calling the delegate using the named methods dm(10); //instantiating the delegate using another named methods dm = new Demo(DisplayMult); //calling the delegate using the named methods dm(4); Console.ReadKey(); } } }
Output
Anonymous Method: 15 Named Method: 20 Named Method: 80
- Related Articles
- C# Anonymous Methods
- What are anonymous methods in C#?
- Anonymous classes in C++
- Anonymous object in Java
- Anonymous goroutines in Golang
- The Anonymous Functions in Python
- Anonymous classes in PHP 7?
- Creating anonymous objects in PHP
- Anonymous Wrapper Functions in JavaScript
- Anonymous function in Dart Programming
- Windows Anonymous Pipe
- PHP Anonymous classes
- PHP Anonymous functions
- Anonymous Union and Structure in C
- Anonymous and Named Pipes in Linux

Advertisements