Saturday, April 21, 2012

Delegates don't have to be intimidating.

using System;
namespace DelegateExample.Models
{
   public delegate Int32 MathyThing(Int32 firstInteger, Int32 secondInteger);
}

 
 

The item above is a delegate! I've been building a silly little calculator app today and the code below uses the delegate above while replacing the CalculationController as documented here. The one action in CalculationController will have handed to it three strings. The first string will contain one of three words: add, multiply, or power. The other two strings are integers in string form. Why should we care about delegates? I am reading C# 4.0 In A Nutshell and I get the impression that one would use a delegate to prep upstream for something that will be needed downstream so to speak. Observe:

namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         
//Step One: Make Sense of Act
         MathyThing mathDelegate;
         switch(act)
         {
            case "add":
               mathDelegate = Adder;
               break;
            case "multiply":
               mathDelegate = Multiplier;
               break;
            case "power":
               mathDelegate = Raiser;
               break;
            default:
               mathDelegate = StatusQuoSustainer;
               break;
         }
         
         
//Step Two: Make Sense of Numeric Data
         Int32 firstInteger = Convert.ToInt32(one);
         Int32 secondInteger = Convert.ToInt32(two);
         
         
//Step Three: Use Act with Numeric Data
         Int32 thirdInteger = mathDelegate(firstInteger, secondInteger);
         var result = new { calulation = thirdInteger.ToString() };
         return RenderJson(result);
      }
      
      private Int32 Adder(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger + secondInteger;
      }
      
      private Int32 Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger * secondInteger;
      }
      
      private Int32 Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         Int32 growingInteger = firstInteger;
         Int32 counterIntger = 1;
         while (counterIntger < secondInteger)
         {
            growingInteger = growingInteger * firstInteger;
            counterIntger++;
         }
         return growingInteger;
      }
      
      private Int32 StatusQuoSustainer(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger;
      }
   }
}

 
 

StatusQuoSustainer above is silly and unneeded. I had to have a default on my switch statement even though there is no way the default will ever be used. I could have used Adder again in lieu of StatusQuoSustainer, but I feared that would be confusing.

No comments:

Post a Comment