switch,case structure

Jun 4, 2012 at 11:31 AM

This is very useful project , thanks.I don't know how to implement a switch,case structure with it. eg:
switch(number)
{
case 0:
number*3;
case 1:
return 5
case 2:
return number*2

}

Can we do it with flee if statements? Please help me.

Jul 4, 2012 at 6:09 PM

I created a class/type to fake switches via method chaining:

 

using System;

namespace FleeExtensions
{
    public class Switch
    {
        private object Source;
        private object Result;
        private bool Completed;

        public static Switch @switch(object source)
        {
            Switch newSwitch = new Switch();
            newSwitch.Source = source;
            return newSwitch;
        }

        public Switch @case(object value, object result)
        {
            if (CheckEqual(value))
            {
                Result = result;
                Completed = true;
            }
            return this;
        }

        public object @default(object defaultResult)
        {
            if (!Completed)
                return defaultResult;
            return Result;
        }

        public bool @default(bool defaultResult)
        {
            if (!Completed)
                return defaultResult;
            return Convert.ToBoolean(Result);
        }

        public string @default(string defaultResult)
        {
            if (!Completed)
                return defaultResult;
            return Convert.ToString(Result);
        }

        public int @default(int defaultResult)
        {
            if (!Completed)
                return defaultResult;
            return Convert.ToInt32(Result);
        }

        public double @default(double defaultResult)
        {
            if (!Completed)
                return defaultResult;
            return Convert.ToDouble(Result);
        }

        private bool CheckEqual(object value)
        {
            if (Completed)
                return false;
            if (Source != null)
                return Source.Equals(value);
            return value == null;
        }
    }
}

Then I make sure to add that as an imported type:

myExpressionContext.Imports.AddType(typeof(Switch));

Then in the scripted text, it's used like:

switch(number).
	case(0, number * 3).
	case(1, 5).
	case(2, number * 2).
	default(YOUR_DEFAULT_RETURN_VALUE)
It worked for Silverlight just fine (haven't tested outside of that).  Note that this implementation also requires that you provide a "default" value case.  You may need to add additional type overloads as needed.