Professional Documents
Culture Documents
1. Delegates:
A delegate is a type that represents a method signature, allowing you to
define a reference to a method.
Delegates can be used to encapsulate methods and pass them as
parameters to other methods or store them in data structures.
They provide a way to achieve callback mechanisms, dynamic method
invocation, and event handling in C#.
2. Defining a Delegate:
You can define a delegate using the delegate keyword, specifying the return
type and parameter list that match the delegate's method signature.
For example:
csharpCopy code
delegate int MathOperation(int x, int y) ;
3. Using Delegates:
You can create instances of delegates and assign them to methods that
match their signature.
You can invoke the delegate, which, in turn, calls the assigned method.
Example:
csharpCopy code
MathOperation add = (x, y) => x + y; MathOperation subtract = (x, y) => x - y; int result1 =
add ( 5 , 3 ); // Invokes the 'add' delegate. int result2 = subtract( 8 , 2 ); // Invokes the 'subtract'
delegate.
4. Delegation in Event Handling:
Delegates are commonly used in event handling in C#.
Events are essentially a way to encapsulate delegates, allowing multiple
subscribers (methods) to be notified when an event occurs.
Example:
csharpCopy code
public class Button { public event EventHandler Click; public void OnClick()
{ Click?.Invoke( this , EventArgs.Empty); } } // Subscribing to the event button.Click += (sender,
args) => Console.WriteLine( "Button clicked!" );
5. Anonymous Methods and Lambda Expressions:
C# provides anonymous methods and lambda expressions, which simplify
delegate usage by allowing you to define inline, anonymous functions.
They are often used with delegates for concise code.
Example:
csharpCopy code
MathOperation multiply = (x, y) => x * y;
Delegation and delegates are fundamental concepts in C# that enable a wide range of
programming patterns, including event-driven programming and callback mechanisms.
They provide a powerful way to separate concerns and make your code more modular
and maintainable.