What is the Delegates in C#

This article will show you the use delegates in C#..
  • 2238

Introduction

Basically delegates are related to the pointer to function. It holds the reference of a method. Delegates are a reference type variable. Delegates reduces the code complexity as we can call a series of method by the signal delegates.

If we want to pass a method as parameter whenever we required the delegates we have to the manipulate the event and call back the method.

Syntax of delegate  

public delegate-typeof-delegate Delegate ();

Example

delegate void MyDelegate(string s);
class
MyClass
{
public static void Hello(string s)
{
Console.WriteLine("  Hello, {0}!", s);
}
public
static void Goodbye(string s)
{
Console
.WriteLine("  Goodbye, {0}!", s);
}
public
static void Main()
{
MyDelegate
a, b, c, d;
a = new MyDelegate(Hello);
b = new MyDelegate(Goodbye);
c = a + b;
d = c - a;
Console
.WriteLine("Invoking delegate a:");
a("A");
Console
.WriteLine("Invoking delegate b:");
b("B");
Console
.WriteLine("Invoking delegate c:");
c("C");
Console
.WriteLine("Invoking delegate d:");
d("D");
Console
.ReadLine();
}
}
}

Output

delegates.jpg

© 2013 dotNetheaven. All rights reserved.