Basics of delegate

What is delegate

  • A delegate is a type safe function pointer.
  • Delegate hold a reference to a function.
  • The signature of the delegate must match the signature of the function, the delegate points to,otherwise we get a compiler error.This is the reason delegates as called type safe function pointers.
  • A delegate is similar to a class, we can create an instance of it, and when we do so, we pass in the function as parameter to the delegate, constructor, and it is to this function the delegate will point to.

Example

using System;
namespace d2cDelegatesSample
{
class Program
{
public delegate void WelcomeWindowDelegate(string inputMeggage);

static void Main(string[] args)
{
WelcomeWindowDelegate objDelegate = new WelcomeWindowDelegate(WelcomeWindow);
objDelegate("Welcome To Desire2Code.com");
}

public static void WelcomeWindow(string inputMessage)
{
Console.WriteLine(inputMessage);
Console.ReadLine();
}
}
}