I am writing a parser which calls some functions dependent on some value.
I can implement this logic with simple switch like this:
switch(some_val)
{
case 0:
func0();
break;
case 1:
func1();
break;
}
or with delegates and a dictionary like this:
delegate void some_delegate();
Dictionary<int, some_delegate> some_dictionary = new Dictionary<int, some_delegate>();
some_dictionary[0] = func0;
some_dictionary[1] = func1;
some_dictionary[some_value].Invoke();
Are these two methods equivalent and which is preferred?
In terms of access, they’re identical: both just check if that specific value has a corresponding result. However, a Dictionary will throw an out-of-bounds exception if you try to access a non-existent key.
The choice should primarily be on re-usability. If you only need to make this branching logic at one point, then using a switch-case is probably makes more sense than storing a variable. If you need to access it repeatedly in separate points, then use the Dictionary to save yourself from just re-pasting the switch-statement repeatedly.