Monday, September 20, 2010

Combining and Abusing Delegates

I had never before thought much about combining delegates until I came across some code that combined them using lambdas, and it got me thinking about other ways to use them. Consider the following example. Note: crazy code ahead!

public class Programmer
{
Action<string> a;

public Programmer(string name)
{
this.Name = name;
}

public string Name { get; set; }

public bool ShouldDesign
{
set
{
if (value)
a += s => { Console.WriteLine(Name + " should design " + s); };
}
}

public bool ShouldDevelop
{
set
{
if (value)
a += s => { Console.WriteLine(Name + " should develop " + s); };
}
}

public bool ShouldDeploy
{
set
{
if (value)
a += s => { Console.WriteLine(Name + " should deploy " + s); };
}
}

public void Work(string programName)
{
a(programName);
}
}

And then used in a console app like this:

static void Main(string[] args)
{
var paul = new Programmer("Paul");
paul.ShouldDesign = true;
paul.ShouldDevelop = true;
paul.ShouldDeploy = false;

paul.Work("my application");

Console.ReadKey();
}

And the output…

image



I do not encourage the kind of code I’ve created here, but maybe this will get you thinking!

0 comments: