Introducing Radical.sh

Forget Code launches a powerful code generator for building API's

Delegates in C#

A delegate in C# is similar to a function pointer in C or C++.

A delegate is a type that references a method.
Once a delegate is assigned a method, it behaves exactly like that method.
The delegate method can be used like any other method, with parameters and a return value.

Syntax:
  1. delegate result-type identifier ([parameters]);

where,
result-type: The result type, which matches the return type of the function.
identifier: The delegate name.
parameters: The Parameters, that the function takes.


An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references.
Any object will do; all that matters is that the method's argument types and return type match the delegate's.
This makes delegates perfectly suited for "anonymous" invocation.

A sample delegate program:

  1. using System;
  2.  
  3. namespace forgetCode
  4. {
  5. delegate void Mydel(string s);
  6.  
  7. class program
  8. {
  9. public static void method1(string a)
  10. {
  11. Console.WriteLine("Hi," + a);
  12. }
  13.  
  14. public static void method2(string b)
  15. {
  16. Console.WriteLine("Hello," + b);
  17. }
  18.  
  19.  
  20. public static void Main()
  21. {
  22.  
  23. Mydel a, b;
  24.  
  25. a = new Mydel(method1);
  26. b = new Mydel(method2);
  27.  
  28. a("Forget Code");
  29. b("Forget Code");
  30. }
  31. }
  32. }



Output:

Hi, Forget Code
Hello, Forget Code


..