Web
Analytics
Delegates in C# | Angular | ASP.NET Tutorials

For Consultation : +91 9887575540

Stay Connected :

Delegate : It is a reference type variable and holds reference to a method. At runtime method reference can be changed.

Base Class: System.Delegate

Declaration of delegate:

delegate <return type> <delegate-name> <parameter list>

Example : public delegate int CalculateArea (string s);

Call Delegate:

  1. Using Invoke method
  2. By Creation object of the delegate.

Using Invoke Method Example:

namespace LambdaExp

{

class Program

{

delegate double CalculateAreaPointer(int radius);

static CalculateAreaPointer cpointer = CalculateArea;

static void Main(string[] args)

{

double area = cpointer.Invoke(12);

Console.WriteLine(area);

Console.ReadLine();

}

 

static double CalculateArea(int radius)

{

return 3.14 * radius * radius;

}

}

 Using Object of Delegate:

namespace LambdaExp

{

class Program

{

delegate double CalculateAreaPointer(int radius);

 

static void Main(string[] args)

{

 

CalculateAreaPointer obj1 = new CalculateAreaPointer(CalculateArea);

CalculateAreaPointer obj2 = new CalculateAreaPointer(square);

double area = obj1(40);

Console.WriteLine(area+ “Square is “+obj2(10));

Console.ReadLine();

}

 

static double CalculateArea(int radius)

{

return 3.14 * radius * radius;

}

static double square(int rad)

{

return rad*rad;

}

}

}

 

Shortcut way to implement Delegates

namespace LambdaExp

{

class Program

{

delegate double CalculateAreaPointer(int radius);

 

static void Main(string[] args)

{

 

CalculateAreaPointer obj1 = new CalculateAreaPointer(

delegate(int radius)

{

return 3.14 * radius * radius;

}

);

CalculateAreaPointer obj2 = new CalculateAreaPointer(

delegate(int squareval)

{

return squareval * squareval;

}

);

double area = obj1(40);

Console.WriteLine(area + “Square is ” + obj2(10));

Console.ReadLine();

}

}

}