Click here to Skip to main content
15,886,258 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Strategy method or Switch statement in C#

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Jun 2011CPOL 6.3K  
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:

C#
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);
        }
    }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
FDW
Netherlands Netherlands
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --