Search code examples
c#inheritanceinterfacepolymorphismimplementation

C#: Using a dictionary of string, interface to reference different classes


I would like to create a dictionary that uses strings as keys to instantiate objects. Here is the start of my dictionary:

Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
{
    {"help",  TerminalCommandHelp},
    {"exit",  TerminalCommandExit},
};

These terminal command classes implement the ITerminalCommand interface as such:

public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand
{
    //contents of class correctly implementing interface
}

The problem is that when I declare and initialize my dictionary, I'm getting an error saying

"TerminalCommandHelp" is a type, which is not valid in the given context.

I thought interfaces could be use abstractly to represent any class that implements from it? Ultimately, when the user looks up a key, I want to create an instance of that particular class. Can someone point out my misunderstanding? Thank you!


Solution

  • //You are trying to pass their type not an instance.
    Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
        {
            {"help",  TerminalCommandHelp},
            {"exit",  TerminalCommandExit},
        };
    
    //Initialize your types into objects and put those in your Dictionary.
    IDictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
        {
            {"help",  new TerminalCommandHelp()},
            {"exit",  new TerminalCommandExit()},
        };