65.9K
CodeProject is changing. Read more.
Home

Strategy method or Switch statement in C#

starIconstarIconstarIconstarIconstarIcon

5.00/5 (1 vote)

Jun 9, 2011

CPOL
viewsIcon

6401

This is what I would do:using System;using NUnit.Framework;using System.Reflection;namespace Profix.Utils.Xpo.UnitTests{ [TestFixture] public class Functions { private void Tax() { Console.WriteLine("Computed Tax."); } private void Sale() {...

This is what I would do:
using System;
using NUnit.Framework;
using System.Reflection;
namespace Profix.Utils.Xpo.UnitTests
{
    [TestFixture]
    public class Functions
    {
        private void Tax() { Console.WriteLine("Computed Tax."); }
        private void Sale() { Console.WriteLine("Computed Sale."); }
        private void Shipping() { Console.WriteLine("Computed Shipping."); }
        public enum MyFunctions { None = 0, Tax, Sale, Shipping }
        public static void Compute(string psMyFunction)
        {
            if (string.IsNullOrWhiteSpace(psMyFunction) == false)
                Functions.Compute((MyFunctions?)Enum.Parse(typeof(MyFunctions), psMyFunction));
            else
                Console.WriteLine("Nothing to compute!");
        }
        public static void Compute(MyFunctions? penumMyFunction)
        {
            if ((penumMyFunction ?? MyFunctions.None) != MyFunctions.None)
                typeof(Functions).GetMethod(penumMyFunction.Value.ToString(), BindingFlags.NonPublic | BindingFlags.Instance).Invoke(new Functions(), null);
            else
                Console.WriteLine("Nothing to compute!");
        }
        [Test]
        public void TestMyFunctions()
        {
            System.Diagnostics.Debugger.Break();
            Functions.Compute(0);
            Functions.Compute((string)null);
            Functions.Compute((MyFunctions?)null);
            Functions.Compute(MyFunctions.Tax);
            Functions.Compute(MyFunctions.Sale);
            Functions.Compute(MyFunctions.Shipping);
        }
    }
}