C# Programming :: Delegate

What is delegate?

A Delegate is a type safe function pointer.That is, it holds reference(Pointer) to a function.

The signature of delegate must match the signature of the function, the delegate points to, otherwise you get a compiler error.This is a reason delegate are called type safe function.

A delegate similar to a class. You can create an instance of it, and when you do so, you pass in the function name as a parameter to the delegate constructor, and it is to this function the delegate will points to.

Tips to remember delegate syntax: Delegate syntax look very much similar to a method with a delegate keyword.


Points to be noted:

  • In Structure is vale type,Class and Interface are reference type.
  • Similarly delegate known as reference type.
  • A Delegate is a type safe function pointer.
  • Delegate points to a function. when you invoke this delegate, the function will be invoked. 

 

Example:

 using System;  
 namespace Practise  
 {  
   public delegate void HelloFunctionDelegate(string Message);  
   class Delegate  
   {  
     public static void Main()  
      {  
       HelloFunctionDelegate del = new HelloFunctionDelegate(Hello);  
       del("Welcome to Delegate");  
     }  
     public static void Hello(string strMessage)  
     {  
       Console.WriteLine(strMessage);  
       Console.ReadLine();  
     }  
   }  
 }