Sir Maxwell Sir Maxwell - 29 days ago 5x
C# Question

Retrieving dictionary<string, Action>

I'm building a parser for a text-based game, well trying is more like it. So I want to store all the possible verbs and nouns into their own dictionary. But I got an error when trying to retrieve the string key from the dictionary...

In my Dictionary class, I create the Verbs dictionary, like so:

public Dictionary<string, Action> Verbs = new Dictionary<string, Action>();

I then proceed to add some value to it:

public void PopulateVerbs()
Verbs.Add("MOVE", Action.MoveAction);

In my VerbAction class, I have methods that do stuff based on input:

Action Move = dictionary.Verbs["MOVE"];

public void MoveAction()
Console.WriteLine("You moved...");

And finally, in my CommandHandler class, I handle the input:

if (InputToken[0] == dictionary.Verbs["MOVE"])

And this is where I get the error, it says that the ["MOVE"] string that I'm trying to retrieve is in fact an action, so I'm a little confused. What am I missing here?


Verbs["MOVE"] will get the value stored with the key "MOVE", so it will return an Action in this case. I assume InputToken is a list of strings, and given that you have a dictionary full of string/action values representing your actions I might try something like this so you don't need a bunch of if checks:


if (InputToken[0] == dictionary.Verbs["MOVE"])

And use the dictionary to your advantage:

Action theAction = dictionary.Verbs[InputToken[0]];

You can condense this further too:


Furthermore, the dictionary is a pretty robust class so you can use its features to start adding error handling checks (if Verbs.ContainsKey, etc)