What is delegates in c#?

Prem Murmu on 2/23/2021 1:23:31 AM

A delegate represents references to methods with a particular parameter list and return type. delegate can be associate its instance with any method with a compatible signature and return type and able to invoke and call through the delegate.

Delegates are used to pass methods as arguments to other methods.

Example:

namespace delegatedemo
{
  //declaring a delegate
 public delegate void DelegateDemo(string msg);        
  class Program
   {
    static void Main(string[] args)
    {
     // set target method
    DelegateDemo del = new DelegateDemo(MSG);
    // or 
     DelegateDemo del1 = MSG;
     // or set lambda expression 
     DelegateDemo del2 = (string msg) =>
     Console.WriteLine(msg);
      // target method
     static void MSG(string message)
     {
      Console.WriteLine(message);
     }
    }
   }


0 Comments on this post

Comments(0)||Login to Comments


InterServer Web Hosting and VPS
  • see more..