delegates

  • Thread starter Thread starter ichor
  • Start date Start date
I

ichor

hi,
i have read about delegates from the msdn site. but fail to understand where
they can be used ?

are they similar to events ?
a good example of where i can use delegates would be helpful
thanx
 
Hello

Imagine delegates as function pointers - you can pass this pointer to a
class which will be able to call this function (a callback) without
knowing about the class that contains the function or any implementation
details.

I have written a method that browses a tree recursively. I need to do
this from a lot of different classes, so I've put that code in a single
method that takes a callback handler. I'm traversing the tree and call
the delegate for every node:


public static void BrowseNodes(TreeNodeCollection nodes,
ClassNodeHandler callbackHandler)
{
foreach (TreeNode node in nodes)
{
ClassNode classNode = node as ClassNode;
if (classNode != null)
{
callbackHandler(classNode);
}

//call recursively
BrowseNodes(node.Nodes, callbackHandler);
}
}



All I have to do now is to create a delegate and pass it along with the
nodes to inspect:

//event handler in a gui
public void OnChangeColor()
{
NodeUtil.BrowseNodes(tree.Nodes, new ClassNodeHandler(ChangeColor));
}


//the callback handler
private void ChangeColor(ClassNode node)
{
node.ForeColor = ...
}



hth, Philipp
 
1. Delegates form the life-blood of Asynchonous progamming model in dotnet.
2. Delegates are what letting you handle events from your user interface
controls.
3. Many more...
 
Back
Top