Saturday, April 21, 2012

The Func of C# makes delegates easier.

More magic from C# 4.0 in a Nutshell: I found it easy to get rid of the independent delegate called MathyThing in its own file here by replacing it with a Func of <Int32,Int32,Int32> shape. I then refactored the controller below to make the potential methods to be given to the Func return strings instead of integers. Why? To distinguish the return value by making it a different type. The Func took a <Int32,Int32,string> shape to accomodate this. The last value is the return value. What is the Func for? As you can see it gets rid of the need to have another file somewhere to keep code for a delegate's shape.

using System;
namespace DelegateExample.Controllers
{
   public class CalculationController : BaseController
   {
      public RenderJsonResult Go(string act, string one, string two)
      {
         
//Step One: Make Sense of Act
         Func<Int32,Int32,string> 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
         string thirdValue = mathDelegate(firstInteger, secondInteger);
         var result = new { calulation = thirdValue };
         return RenderJson(result);
      }
      
      private string Adder(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger + secondInteger).ToString();
      }
      
      private string Multiplier(Int32 firstInteger, Int32 secondInteger)
      {
         return (firstInteger * secondInteger).ToString();
      }
      
      private string Raiser(Int32 firstInteger, Int32 secondInteger)
      {
         Int32 growingInteger = firstInteger;
         Int32 counterIntger = 1;
         while (counterIntger < secondInteger)
         {
            growingInteger = growingInteger * firstInteger;
            counterIntger++;
         }
         return growingInteger.ToString();
      }
      
      private string StatusQuoSustainer(Int32 firstInteger, Int32 secondInteger)
      {
         return firstInteger.ToString();
      }
   }
}

No comments:

Post a Comment