0% found this document useful (0 votes)
14 views10 pages

Delegate in

Uploaded by

Amit Baranwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views10 pages

Delegate in

Uploaded by

Amit Baranwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Delegates in .

NET
• What is a Delegate?

• - A type-safe reference to a method.

• - Allows methods to be assigned to variables and passed as parameters.

• - Useful for event handling and callback methods.


Types of Delegates
• 1. Single-cast Delegate:

• - Holds a reference to a single method.

• 2. Multicast Delegate:

• - Can hold references to multiple methods.

• - Executes methods in order of addition.


Assign Methods to Delegates
• Syntax to Assign a Method:

• public delegate void MyDelegate(string message);

• MyDelegate del = MethodName;

• - The method assigned must match the delegate's signature.

• - Supports reassignment and chaining methods.


Invoking a Delegate
• Invoke a Delegate:

• del("Hello, Delegates!");

• - Calls the assigned method(s).

• - Can check for null before invoking.


Pass Delegates as Parameters
• Delegates can be passed to methods for dynamic behavior.

• - Enables flexible and reusable code.

• Example:

• public void ExecuteAction(MyDelegate del)

• {

• del("Executing action!");

• }
Lambda Expressions
• Shorthand syntax for inline methods.

• - Makes delegate code more concise.

• Example:

• MyDelegate del = (msg) => Console.WriteLine(msg);

• del("Hello with Lambda!");


Multicast Delegates
• Allows chaining multiple methods in one delegate.

• - Use += to add methods and -= to remove.

• Example:

• del += Method1;

• del += Method2;

• del("Multicast Delegate Example");


Using Delegates with Events
• Delegates form the foundation for events.

• - Useful for creating publish-subscribe mechanisms.

• Example:

• public event MyDelegate OnMessageReceived;

• OnMessageReceived?.Invoke("Event triggered!");
Benefits and Drawbacks of Delegates
• Benefits:

• - Simplifies complex logic with callbacks.

• - Enables flexible and modular code.

• - Supports event-driven programming.

• Drawbacks:

• - Hard to debug when used excessively.

• - Indirect calling may reduce performance.

• - Risk of null reference exceptions.


Summary
• Delegates are powerful and flexible tools in .NET.

• - Useful for callbacks, events, and dynamic method execution.

• - Support Lambda expressions and Multicasting.

• - Balance usage to avoid performance and debugging issues.

You might also like