How to used Delegate in c#

What is Delegate?

  • A type called a delegate is used to express pointers to methods that have a certain argument list and return type.
  • A delegate’s instance can be connected to any method with a compatible signature and return type once it has been created.
  • The delegate instance can be used to call the method.

How to Used Delegate?

  • A delegate is a type that, like a function pointer in C and C++, securely encapsulates a method.
  • Delegates are object-oriented, type-safe, and secure in contrast to C function pointers.
  • A delegate’s name indicates the type of that delegate.
  • A method that accepts a string as an argument and returns void can be encapsulated in a delegate named Del in the example below:
public delegate void Del(string name);
  • Create a method for a delegate.
public static void DelegateMethod(string name)
{
    Console.WriteLine(name);
}
  • Instantiate the delegate.
Del handler = DelegateMethod;
  • Call the delegate.
handler("The Code hubs");
  • Callbacks are frequently used in conjunction with custom comparison methods that are delegated to sort methods.
  • It enables the caller’s code to be incorporated into the sorting formula.
public static void CallbackMethod(int par1, int par2, Del callback)
{
    callback("The number is: " + (par1 + par2).ToString());
}
  • Then you may call that method using the delegate you generated earlier:
CallbackMethod(1, 2, handler);
  • and get the terminal to output the following information:
The number is: 3

 

Submit a Comment

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

Subscribe

Select Categories