.

C Sharp Delegates Tutorials

DELEGATES

  • It is a variable of reference type which holds the method or the function reference
  • It is a pointer to a method in c, c++
  • At the time running , the reference could be modified
  • Its mainly used for event implementation
  • It also used in methods call back
  • Its base classNameis System. Delegate className

Delegate Declaration

  • It finds the referencing method by the delegate
  • It points a method
  • The method has the similar signature like delegate

Declaration Syntax

delegate returntype delegatename (parameter_list)

Example

public delegate int my_sample_delegate (int i);

The delegate is used to point a method which has one integer parameter and integer return type

Delegate Instantiation

  • It can be done after the declaration of a delegate,
  • Delegate object is to be generated with a ‘new’ keyword and it is to be linked to a represented method
  • Delegate creation should be oriented with the parameters that are passing which is to be identical with method call

Example

public delegate void my_sample_delegate (string s);

my_sample_delegate d1 = new my_sample_delegate(WriteToScreen);

my_sample_delegate d1 = new my_sample_delegate(WriteToFile);

Using Delegates

  • The below example demonstrates the delegate usage
  • printString delegate is employed to reference method
  • It obtains string as an input parameter and returns void Here the delegate is used to call 2 methods
  • The 1st prints the string and the 2nd one prints to a file

Example

delegates image 1
.