Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using enum item to call a method

Tags:

c#

enums

I have an enum with 30 items in it. Each item has a corresponding function with the same name. I would like to be able to call the function by referencing the enum at a certain position.

So if the value at enum[0] = Foo, I would like to be able to call Foo(string bar) by using something like enum(0)("foobar")

In the end the point is I am running each function as a task like so:

enum Test { AA, BB, CC, DD ....}
tasks[0] = Task.Run(() => { prices[0] = AA("a string"); });
tasks[1] = Task.Run(() => { prices[1] = BB("a string"); });
tasks[2] = Task.Run(() => { prices[2] = CC("a string"); });
//for 30 tasks

What I would like to do is something along the lines of:

enum Test { AA, BB, CC, DD ....}
for (int i = 0; i < 30; i++)
{
    tasks[i] = Task.Run(() => { prices[i] = (Test)i("a string"); });
}
Task.WaitAll(tasks.ToArray());

Is this something that is even possible?

EDIT:

The enum relates to controls on a form so i have an array of textboxs, label and a array of prices that is populated with the results of the functions:

enum Dealers { Dealer1, Dealer2 ... Dealer29, Dealer30 };

static int noOfDealers = Enum.GetNames(typeof(Dealers)).Length;
decimal[] prices = new decimal[noOfDealers];
TextBox[] textBox = new TextBox[noOfDealers];
Label[] boxes = new Label[noOfDealers];

for (int i = 0; i < noOfDealers; i++)
{
    textBox[i] = Controls.Find("txt" + (Dealers)i, true)[0] as TextBox;
    boxes[i] = Controls.Find("box" + (Dealers)i, true)[0] as Label;
    prices[i] = 0;
}

//RUN 30 TASKS TO POPULATE THE PRICES ARRAY

for (int i = 0; i < noOfDealers; i++)
{
   textBox[i].Text = "£" + prices[i].ToString();
}
//LOOP THROUGH PRICES ARRAY AND FIND CHEAPEST PRICE, THEN COLOUR THE LABEL BACKGROUND GREEN FOR THE TEXT BOX WITH THE NAME AT ENUM VALUE WHATEVER I IS

I guess i am just trying to make my code as concise as possible, there is the potential for the amount of tasks to double and didn't want to end up with 60 lines to populate the tasks array

like image 820
Tom Carroll Avatar asked Dec 18 '22 12:12

Tom Carroll


1 Answers

I would create dictionary and map enum to actions:

  Dictionary<Test, Func<string,double>> actions = new Dictionary<Test, Func<string,double>>()
            {
                {Test.AA, (x) => { return 5;}},
                {Test.BB, (x) => { return 15; }},
            }; //x is your string

            var res = actions[Test.AA]("hello");
like image 148
MistyK Avatar answered Dec 24 '22 02:12

MistyK