Dgameman1 Dgameman1 - 3 months ago 6
C# Question

How can I put a variable in this part of my code?

I have two examples

Primary.Teal800, Primary.Teal900, Primary.Teal500, Accent.LightGreen400, TextShade.WHITE


and

Convert.ToInt32(textBox.Text)


The part after the
.
I want a variable. For example, the pseudo-code for this would be

var color = "Teal";
Primary.color + 800, Primary.color + 900, Primary.color + 500, Accent.LightGreen400, TextShade.WHITE


or

var toWhich = "ToInt32";
Convert.toWhich(textBox.Text)


Would there be any way to do that?

I'm accessing an enum

Answer

Since Primary is an enum, you can use Enum.Parse. Make a helper method for it:

static Primary GetPrimaryColor(string name, int number) {
    return (Primary)Enum.Parse(typeof(Primary), name+number);
}

Calling the helper lets you do this:

var color = "Teal";
GetPrimaryColor(color, 800), GetPrimaryColor(color, 900), ...
Comments