What is Delegate in C#

What is Delegate in C#?

C# delegates are pointers to functions or methods. A delegate is a reference type variable that holds the reference to a method. The reference can be changed at the runtime. Delegates are especially used for implementing events and the call-back methods. All the delegates are implicitly derived from the System.Delegate class.

Simple Delegate Example:

public class WebTools

{
    //Declare Delegate

    public delegate int PointerToAddFunction(int i, int y);

    private int Add(int i, int y)

    {

        return i + y;

    }

}

protected void btnPreview_Click(object sender, EventArgs e)

{

    // Create Delegate Reference

    PointeToAddFunction myptr = null;

    // Point the reference to the add method

    myptr = this.Add;

    // Invoke the method through delegate object

    Label_Result.Text = myptr.Invoke(20, 10).ToString();

}

Next Recommended Reading Remove AM PM from Time String using C#