ttajic
6/1/2016 - 8:06 AM

Switch based on type aka TypeSwitch

Switch based on type aka TypeSwitch

    /// <summary>
    /// TypeSwitch.Do(
    //  sender,
    //  TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
    //  TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
    //  TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
    /// </summary>
    internal static class TypeSwitch
    {
        public class CaseInfo
        {
            public bool IsDefault { get; set; }
            public Type Target { get; set; }
            public Action<object> Action { get; set; }
        }

        public static void Do(object source, params CaseInfo[] cases)
        {
            if (source == null)
                return;

            var type = source.GetType();
            foreach (var entry in cases)
            {
                if (entry.IsDefault || entry.Target.IsAssignableFrom(type))
                {
                    entry.Action(source);
                    break;
                }
            }
        }

        public static CaseInfo Case<T>(Action action)
        {
            return new CaseInfo()
            {
                Action = x => action(),
                Target = typeof(T)
            };
        }

        public static CaseInfo Case<T>(Action<T> action)
        {
            return new CaseInfo()
            {
                Action = (x) => action((T)x),
                Target = typeof(T)
            };
        }

        public static CaseInfo Default(Action action)
        {
            return new CaseInfo()
            {
                Action = x => action(),
                IsDefault = true
            };
        }
    }
    
    
    
  private string GetValueFromCRMType(object value)
  {
    string result = null;
    TypeSwitch.Do(
    value,
    TypeSwitch.Case<EntityReference>((eref) => result = eref != null ? string.Format("{0}:{1}:{2}", eref.Id, eref.LogicalName, eref.Name) : null),
    TypeSwitch.Case<Money>(m => result = m != null ? m.Value.ToString("C") : null),
    TypeSwitch.Case<OptionSetValue>(o => result = o != null ? o.Value.ToString() : null),
    TypeSwitch.Default(() => result = string.Format("{0}", value)));
    return result;
  }