C# · CodeProject · Dotnet

Delegates may reduce usage of conditional statements TIP (Beginner/Intermediate)

Dear Reader,

Delegates are of a great gift to us in C#, and i really love working with all the time although i agree with you that using it extensively may harm as too much of any thing is poison 🙂

But may be you could still point out to me any example which uses extensively delegates and its causing some problem.

As i was writing some code and i wanted to execute similar signature methods based on some conditional inputs, again i am presenting here random code and not the exact code i am working on:

Lets assume i have below code:

static void Main(string[] args)
Program p = new Program();

Console.WriteLine("Enter your choice of Char : X, Y, Z, A, B");
char c = Console.ReadLine()[0];

if (c == 'A')
else if (c == 'B')
else if (c == 'X')
else if (c == 'Y')
else if (c == 'Z')


The body of those methods is not important here. So you can just ignore. Obviously the above code is not good style of coding, yes we may replace it with just switch statement. Again problem due to various reason: maintainability is poor, complexity, etc.

But my main concern was to reduce the cyclomatic complexity in this code chunk.  So while i was thinking for an alternative solution i remembered that i had read below solution some where very long back. So hence wanted to share the same to others 🙂

I changed the above code with delegates and this is what i came up with :

            Dictionary<char, myDelegate> myDelegateDictionary = new Dictionary<char, myDelegate>();

            myDelegateDictionary.Add('X', p.MethodX);
            myDelegateDictionary.Add('Y', p.MethodY);
            myDelegateDictionary.Add('Z', p.MethodZ);
            myDelegateDictionary.Add('A', p.MethodA);
            myDelegateDictionary.Add('B', p.MethodB);

            myDelegate mydel;
            myDelegateDictionary.TryGetValue(c, out mydel);

            if (mydel != null)

I agree that the maintainability factor did not differ much, but the complexity has greatly reduced.

Happy Coding 🙂

P.S: Your comments/votes are much appreciated.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s