1

I'm creating an input text box on Forms, and I want specific commands to called certain procedures, e.g. "time" once entered would return with a MessageBox displaying the current time.

I currently use cases but wish to call the functions directly from a dictionary

private void enter_button_Click(object sender, EventArgs e)
        {
            Dictionary<string, Int64> commandDict = new Dictionary<string, Int64>()
            {
                ["Do1"] = 1,
                ["Do2"] = 2,
                ["Do3"] = 3
            };
            long caseInput = 0;
            try
            {
                caseInput = Convert.ToInt64(commandDict[(textBox1.Text).ToLower()]); 
//Returns dict value as long integer /\
            }
            catch { }
            switch (caseInput)
            {
                case 1:
                    Console.WriteLine("Do Thing 1")
                    break;
                case 2:
                    Console.WriteLine("Do Thing 2")
                    break;
                case 3:
                    Console.WriteLine("Do Thing 3") 
                    break;
                default:
                    Console.WriteLine("Incorrect Input")
                    break;

I want case 1,2 and 3 to be separate functions (their functionality has been downplayed but none return a value and none have input parameters). I would like commandDict (my current dictionary, to call these 3 procedures when the text "Do1" etc is inputted into "textBox1.Text".

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
Isaac Harris
  • 19
  • 1
  • 5

3 Answers3

4

You can use code like below. Dictionary should help you to achieve what you want to do.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

public class Test
{
    public static void Main(string[] args)
    {
        Dictionary<string, Action> dict = new Dictionary<string, Action>();
       dict.Add("Do1", ActionDo1);  
        dict.Add("Do2", ActionDo1); 

        dict["Do1"]();
    }

    public static void ActionDo1()
    {
        Console.WriteLine("The Do1 is called");
    }

    public static void ActionDo2()
    {
        Console.WriteLine("The Do2 is called");
    }


}

Hope this helps.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37
2

Then declare your dictionary as Dictionary<string, Action>, and add the function names as values to your dictionary.

Nick
  • 4,787
  • 2
  • 18
  • 24
0

This way:

class Program
{
    private static Dictionary<string, Delegate> methods = new Dictionary<string, Delegate>();
    static void Main(string[] args)
    {
        methods.Add("Test1", new Action<string>(str => { Console.WriteLine(str); }));
        methods.Add("Test2", new Func<string, bool>(str => { return string.IsNullOrEmpty(str); }));
    }
}

You will be able to add to the dictionary Action which is equal to a void method and Func which can take inputs and return values.

Marco Salerno
  • 5,131
  • 2
  • 12
  • 32