Click here to Skip to main content
15,921,454 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
In which scenario we basicaly use delegate in dot net.plz explain me with live example.
Posted

A delegate is a type that safely encapsulates a method, similar to a function pointer in C and C++. Unlike C function pointers, delegates are object-oriented, type safe, and secure. The type of a delegate is defined by the name of the delegate.
An small example:
C#
// Create a method for a delegate.
public static void DelegateMethod(string message)
{
    System.Console.WriteLine(message);
}

And now declare and just call..
C#
// Instantiate the delegate.
Del handler = DelegateMethod;

// Call the delegate.
handler("Hello World");


Some scopes where delegates are used:
1. Event handlers (for GUI and more)
2. Starting threads
3. Callbacks (e.g. for async APIs)
4. LINQ and similar (List.Find etc)
5. Anywhere else where I want to effectively apply "template" code with some specialized logic inside (where the delegate provides the specialization)

Some live examples you can view here:
The Power of Delegates in C#[^]
C# - Delegates 101 - A Practical Example[^]
http://stackoverflow.com/questions/2019402/when-why-to-use-delegates[^]
 
Share this answer
 
v3
Refer to below links where Sergey explained it in very concise way.

What are the advantages of delegates in C#.NET?[^]

What is the Extra Advantage of Delegate[^]

Why we use Delegates[^]

Dynamic Method Dispatcher[^]

Regards.. :laugh:
 
Share this answer
 
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900