how to use delegate in csharp

Delegates are a type in C# used to create references to methods. They can be thought of as a pointer or reference to a function. Delegates are particularly useful in event-based programming, where they can be used to define callback methods.

Here are the steps to use delegates in C#:

  1. Define the delegate:
main.cs
delegate int Calculator(int a, int b);
39 chars
2 lines
  1. Create a method that matches the delegate signature:
main.cs
static int Add(int a, int b)
{
    return a + b;
}
51 chars
5 lines
  1. Create an instance of the delegate:
main.cs
Calculator calc = Add;
23 chars
2 lines
  1. Invoke the method through the delegate:
main.cs
int result = calc(3, 5); // returns 8
38 chars
2 lines

Delegates can also be used with anonymous methods and lambda expressions:

main.cs
// using anonymous method
Calculator multiply = delegate(int a, int b)
{
    return a * b;
};

// using lambda expression
Calculator divide = (a, b) => a / b;
159 chars
9 lines

Delegates are commonly used in conjunction with events in C#. Events are a way for a class to notify any listeners that something has occurred. Here's an example of how to use an event with a delegate:

main.cs
public class Counter
{
    public delegate void ThresholdReachedEventHandler(object sender, EventArgs e);

    public event ThresholdReachedEventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        ThresholdReached?.Invoke(this, e);
    }

    public void Count(int countTo)
    {
        for (int i = 0; i <= countTo; i++)
        {
            if (i == 10)
            {
                OnThresholdReached(EventArgs.Empty);
            }
        }
    }
}
505 chars
23 lines

In this example, the ThresholdReached event is associated with the delegate type ThresholdReachedEventHandler. The OnThresholdReached method is called when the count reaches 10, and any listeners to the event will be notified.

gistlibby LogSnag