What is Delegate in C# Why and How to Use

A Delegate is a reference type that refers to a method.it use to pass methods as arguments to other method. Which is used to invoke the method at a later time. It is useful for implementing events and callbacks.

Delegate can be declare using the delegate keywords

Delegate int MyDelegates(int k,int z);
 public static int add(int k,int z)
    {
        return k + z;
    }

Create delegate instance and pass it the method

MyDelegates del=new MyDelegates(Add);

int result= del(10,5);

It can also use anonymous methos and Lambda expressions to create delegates.

For Example

mydel del = (k, z) => k + z;

int result = del(110, 60);

Delegate – Passing as Argument

public delegate void Mydelegates(string Message);
public delegate int mydel(int k, int z);
class program
{
    static void Main(string[] args)
    {
        Mydelegates mydelegates = Delegateclass.delmethod;
        invokedelegates(mydelegates);

        mydel del = (k, z) => k + z;

        int result = del(110, 60);

        mydel mydel = new mydel(add);

        Console.WriteLine("Add "+ mydel(50,100));

      
    }
    public static int add(int k,int z)
    {
        return k + z;
    }

    public static void invokedelegates(Mydelegates md)
    {
        md("Hi! Welcome");
    }

    public class Delegateclass
    {
        public static void delmethod(string msg)
        {
            Console.WriteLine("Method with parameters:" + msg);
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *