Delegates: Example in C#

When would you need a delegate?
When you want to delegate responsibility for some piece of work elsewhere without creating a compile time dependency.

If you find yourself in a situation where you feel like the argument to a method should be another method, a delegate may be appropriate.

using System;

//Similar to a function prototype
public delegate void DoStuffDelegate(string s);

public class Test{
	public static void Main(string[] args){
		SomeOtherClass someOtherClass = new SomeOtherClass();

		//Call the DoSomething method on our object instance, passing it various
		//pointers to functions -- any will do as long as they match the delegate
		//function prototype
		someOtherClass.DoSomething(new DoStuffDelegate(PrintUpper));
		someOtherClass.DoSomething(new DoStuffDelegate(PrintLower));

		//note that you can delegate anything! -- here's a delegation to a static method
		someOtherClass.DoSomething(new DoStuffDelegate(SomeThirdClass.PrintReverse));
	}

	public static void PrintUpper(string s){
		Console.WriteLine(s.ToUpper());
	}
	
	public static void PrintLower(string s){
		Console.WriteLine(s.ToLower());
	}
}

public class SomeOtherClass{

	//This method knows about the function prototype of DoStuffDelegate(string), 
	//but it doesn't know at compile time what it's going to get
	public void DoSomething(DoStuffDelegate doStuffDelegate){
		doStuffDelegate("This is like a blind date -- I don't know who I'm going to get!");
	}
}

public static class SomeThirdClass{
	public static void PrintReverse(string s){
		for(int i = s.Length-1; i >= 0; --i)
			Console.Write(s[i]);
	}
}
Output:
jknight@shadowbox:/tmp$ mono Delegate.exe 
THIS IS LIKE A BLIND DATE -- I DON'T KNOW WHO I'M GOING TO GET!
this is like a blind date -- i don't know who i'm going to get!
!teg ot gniog m'I ohw wonk t'nod I -- etad dnilb a ekil si sihT
jknight@shadowbox:/tmp$ 

Categories

,
| Comments (0)TrackBacks (0)

0 TrackBacks

Listed below are links to blogs that reference this entry: Delegates: Example in C#.

TrackBack URL for this entry: http://www.rootsilver.com/mt-tb.cgi/82

Leave a comment