Web
Analytics
Delegates in C# - Tutorial

For Consultation : +91 9887575540

Stay Connected :

  • Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object.
  • The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
  • Delegates are especially used for implementing events and the call-back methods. All delegates are implicitly derived from theDelegateclass.
  • A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type.

Delegates

First off, a delegate is a type, i.e. a class. It’s a special class (you’ll see why in a sec), but still, it’s just a class.
That means that like any other class, in order to be used, it must be:

  • declared and
  • instantiated

 

This will result in an object. That object can then be:

  • invoked

 

Syntax for delegate declaration is:

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

 

Declaring Delegates

Delegate declaration determines the methods that can be referenced by the delegate. A delegate can refer to a method, which has the same signature as that of the delegate.

For example, consider a delegate:

public delegate int AreaCalculator (int s);

The preceding delegate can be used to reference any method that has a single int parameter and returns an int type variable.

Once a delegate type is declared, a delegate object must be created with the new keyword and be associated with a particular method. When creating a delegate, the argument passed to thenew expression is written similar to a method call, but without the arguments to the method. For example:

public delegate int AreaCalculator (int s);…CircleArea CA = new CircleArea (GetCircle);SquareArea SA = new SquareArea (GetSquare);

Download

https://youtu.be/gY-IIpF0XBI

Select your currency