Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dictionary Switch - Proves that you can use a dictionary to work the same as a switch making it easier to maintain and more flexible.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionarySwitch
{
public class DataChecker
{
private IDataModifier dataModifier;
private Dictionary<string, Func<int, int>> dictionary;
public DataChecker(IDataModifier dm) {
dataModifier = dm;
GenerateDictionary();
}
public int CheckData(string data, int val)
{
if (dictionary.ContainsKey(data)){
return dictionary[data].Invoke(val);
}
return 0;
}
private void GenerateDictionary()
{
dictionary = new Dictionary<string, Func<int, int>>
{
{"yes", dataModifier.Yes },
{"no", dataModifier.No },
{"maybe", dataModifier.Maybe },
{"blahblah", dataModifier.Maybe },
{"haha", dataModifier.Haha },
{"I don't know", dataModifier.IDontKnow },
{"stuff", dataModifier.Stuff },
{"sometimes", dataModifier.SomeTimes },
{"whenever", dataModifier.Whenever },
{"never", dataModifier.Never },
{"always", dataModifier.Always }
};
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionarySwitch
{
public class DataModifier : IDataModifier
{
public int Always(int val)
{
return val + 9;
}
public int BlahBlah(int val)
{
return val - 99;
}
public int Haha(int val)
{
return val + 100;
}
public int IDontKnow(int val)
{
return val + 432;
}
public int Maybe(int val)
{
return val - 1;
}
public int Never(int val)
{
return val--;
}
public int No(int val)
{
return val + 4;
}
public int SomeTimes(int val)
{
return val + 0;
}
public int Stuff(int val)
{
return val - 2;
}
public int Whenever(int val)
{
return val++;
}
public int Wherever(int val)
{
return val++;
}
public int Yes(int val)
{
return val + 2;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionarySwitch
{
public interface IDataModifier
{
int Yes(int val);
int No(int val);
int Maybe(int val);
int BlahBlah(int val);
int Haha(int val);
int IDontKnow(int val);
int Stuff(int val);
int SomeTimes(int val);
int Whenever(int val);
int Wherever(int val);
int Never(int val);
int Always(int val);
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DictionarySwitch
{
public static class Program
{
public static DataChecker checker = new DataChecker(new DataModifier());
static void Main(string[] args)
{
DictionarySwitch();
Console.ReadKey();
}
public static void DictionarySwitch()
{
int val = checker.CheckData("yes", 0);
Console.WriteLine(val.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment