>static class Test_Switch > { > internal static void Go() > { > GroupMember groupMember = new GroupMember(1, "Gregory", "Adam", 234, "none"); > MKVP mkvp = new MKVP("LAST", "Alan"); > > new Switch() > .Case(() => mkvp.Key == "FIRST", delegate { groupMember.FirstName = mkvp.Value; } ) > .Case(() => mkvp.Key == "LAST", delegate { groupMember.LastName = mkvp.Value; }) > .Default(delegate { throw new Exception("No otherwise/default"); }) > .Execute(); > > Console.WriteLine("{0} {1} ", groupMember.FirstName, groupMember.LastName); > } > } > class MKVP > { > public string Key; > public string Value; > public MKVP(string key, string value) > { > Key = key; > Value = value; > } > } > class GroupMember > { > public int PrimaryKey; > public string FirstName; > public string LastName; > public long GuestNo; > public string Notes; > public GroupMember(int primaryKey, string firstName, string lastName, long guestNo, string notes) > { > PrimaryKey = primaryKey; > FirstName = firstName; > LastName = lastName; > GuestNo = guestNo; > Notes = notes; > } > } >>
> class Switch > { > bool HadDefault = false; > List<Tuple<Func<bool>, Action>> Cases = new List<Tuple<Func<bool>,Action>>(); > > internal Switch Case(Func<bool> predicate, Action action) > { > CheckDefault(); > if (predicate == null) > throw new ArgumentNullException("predicate"); > > CheckAction(action); > Cases.Add(new Tuple<Func<bool>, Action>(predicate, action)); > > return this; > } > internal Switch Default(Action action) > { > CheckDefault(); > CheckAction(action); > > Cases.Add(new Tuple<Func<bool>,Action>(() => true, action)); > HadDefault = true; > > return this; > } > > internal void Execute() > { > foreach( var item in Cases ) > if( item.Item1() ) > { > item.Item2(); > break; > } > } > void CheckDefault() > { > if( HadDefault ) > throw new Exception("Sorry, already a Default"); > } > void CheckAction(Action action) > { > if( action == null ) > throw new ArgumentNullException("action"); > } > } >For readability you could encapsulate the rules for GroupMember in their own class? :
internal class GroupMemberSwitch : Switch { public GroupMemberSwitch(GroupMember member, MKVP mkvp) { Case(() => mkvp.Key == "FIRST", delegate { member.FirstName = mkvp.Value; }); Case(() => mkvp.Key == "LAST", delegate { member.LastName = mkvp.Value; }); Default(delegate { throw new Exception("No otherwise/default"); }); } }then:
GroupMember groupMember = new GroupMember(1, "Gregory", "Adam", 234, "none"); MKVP mkvp = new MKVP("FIRST", "Alan"); new GroupMemberSwitch(groupMember, mkvp).Execute();(requires Switch.Execute() to be virtual)