Pages

Thursday, April 23, 2009

Delegates in C#

A delegate in C# is like a function pointer in C/C++, except in C# they are type-safe.
Delegate is a type that wraps a method call. Delegate instance can be passed between methods like a type and it can be invoked like a method.

There's a three way how to create and use a delegate.
  1. Create an instance of a delegate by explicitly initializing it with a method that is defined somewhere in the code. This way is used in .Net Framework version 1.0.
  2. Create an anonymous method for initializing delegate. This way is used in .Net Framework version 2.0.
  3. Use lambda expressions. This way is used in .Net Framework version 3.0 (and above).

Below is a source code you can use to see how to use delegates.

    1 using System;
    2 
    3 namespace DelegateTest
    4 {
    5   class Tester
    6   {
    7     // Create a delegate instance. This one takes one parameter, which is a string type
    8     delegate void TestDelegate(string s);
    9 
   10     // The method associated with the named delegate
   11     // (same signature as delegate has)
   12     static void DelegateMethod(string s)
   13     {
   14       Console.WriteLine(s);
   15     }
   16 
   17     static void Main(string[] args)
   18     {
   19       // 'Original way' of using delegates 
   20       TestDelegate firstTest = new TestDelegate(DelegateMethod);
   21 
   22       // Using .Net 2.0 anonymous method for initializing delegate
   23       TestDelegate secondTest = delegate(string s) { Console.WriteLine(s); };
   24 
   25       // .Net 3.0 gives us lambda expressions
   26       // The type of s is inferred by the compiler
   27       TestDelegate thirdTest = (s) => { Console.WriteLine(s); };
   28 
   29       // Invoke delegates
   30       firstTest("Hello, I'm the first delegate");
   31       secondTest("And I'm second delegate, .Net 2.0 style");
   32       secondTest("Greetings from delegate number three, with some lambda expression goodness");
   33 
   34       Console.WriteLine();
   35 
   36       Console.ReadLine();
   37     }
   38   }
   39 }

For more information, check link below:
The Evolution of Delegates in C# in MSDN

No comments:

Post a Comment