Jerry Nixon on Windows: Creating a CallBack with anonymous delegates

Jerry Nixon on Windows

Monday, March 24, 2008

Creating a CallBack with anonymous delegates

With a callback, you tell one method another method to call when processing is complete. It's cool.

Here's an example use: let's say you need to call Save() and when save is complete you want to call Close(). That's easy unless Save() is asynchronous. In that case, pass Close() as a callback delegate to the Save() method [something like: Save(CloseDelegate callback)]. When the save function is complete, it can call Close() for you. Easy enough.

Here's a simple console application to show you how to do it. Just create a console project and paste this into your Program.cs file. I wrote this in Visual Studio 2008. Here you go:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplicationCallBack
{
class Program
{
static void Main(string[] args)
{
RemoteClass _RemoteClass;
_RemoteClass = new RemoteClass();
_RemoteClass.Click(new ParentClass());
}
}

class ChildClass
{
public string Text
{
get;
set;
}
public ChildClass(string text)
{
this.Text = text;
}
}

class ParentClass
{
List<ChildClass> m_List = new List<ChildClass>();
public ParentClass()
{
m_List.Add(new ChildClass("Wes"));
m_List.Add(new ChildClass("Eric"));
m_List.Add(new ChildClass("Jerry"));
}
public delegate void MyDelegateFound(ChildClass child);
public delegate void MyDelegateNotFound(string name);
public void GetchildClass(string name,
MyDelegateNotFound myDelegate,
MyDelegateFound myDelegateFound)
{
foreach (ChildClass _Item in m_List)
{
if (_Item.Text == name)
{
myDelegateFound.Invoke(_Item);
return;
}
}
myDelegate.Invoke(name);
}
}

class RemoteClass
{
public void Click(ParentClass centralClass)
{
ParentClass.MyDelegateFound _MyDelegateFound;
_MyDelegateFound =
new ParentClass.MyDelegateFound(delegate(ChildClass child)
{
Console.WriteLine("Found: " + child.Text);
});

ParentClass.MyDelegateNotFound _MyDelegateNotFound;
_MyDelegateNotFound =
new ParentClass.MyDelegateNotFound(delegate(string name)
{
Console.WriteLine("Not Found: " + name);
});

centralClass.GetchildClass("Jerry",
_MyDelegateNotFound, _MyDelegateFound);
centralClass.GetchildClass("JerryFAIL",
_MyDelegateNotFound, _MyDelegateFound);
}
}
}