Free Information Technology Magazines and eBooks

Friday, May 22, 2009

How to use delegates in C#

A Delegate is something like function pointers. It is an object that is created to refer to a static method and then used to call this method. Using a delegate allows the coder 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 knowing at compile time which method will be invoked. But Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.


For this article, I will demonstrate How to use delegates using a very simple C# example.

Let's create a sample function and named it as ParseString.

static string ParseString(string str)
{
return str.Replace("'", "");
}


Declare the delegate for the ParseString function.

public delegate string DelegateParser(string str);


Now instantiate the delegate and invoke the function through the delegate.

string mystring = Console.ReadLine();
//Instantiate the delegate
DelegateParser parser = new DelegateParser(ParseString);
//Call the delegate
Console.WriteLine(parser(mystring));


That's how simple it is. Here is the complete code:

static string ParseString(string str)
{
return str.Replace("'", "");
}

public delegate string DelegateParser(string str);

static void Main(string[] args)
{
string mystring = Console.ReadLine();
DelegateParser parser = new DelegateParser(ParseString);
Console.WriteLine(parser(mystring));
Console.ReadKey();
}


I often often use delegates to encapsulate my libraries so that actual functions names are not visible to other programmers. This is an effective way to standardize coding.

For more C# tips and tricks, subscribe now

0 comments: