How can I reference a variable whose name is determined by a string? (C#)

For example, I have 3 lights; Red, Green Blue. I have one script (call it Switch) that says “Red light has been switched on” by passing the string “red” to another script (call it Lights). Lights has a boolean value for the red light called redLight that should be set to “true” when Switch sends the string “red” over, so it would be convenient to be able to have a line or two of code that takes “red”, adds “Light” to it (to generate redLight), then sets that equal to true. Alternatively Switch might have sent “Blue”, “Yellow”, whatever.

I know this can be done with a series of if statements, I suppose it might be accomplished by using dictionaries, and I’m sure there are other ways to do this, but i know this type of functionality exists in other languages (see “eval” in MATLAB, for example). Does such a functionality exist in C#?

What you are looking for is achieved through reflection. The caveat is this only works with public properties or members.

    public bool RedLight { get; set; }

    private void SetLight(string name, bool value)
    {
        this.GetType().GetProperty(name).SetValue(this, value);
    }

    SetLight("RedLight", true);

Or if RedLight is just member variable, use GetMember() instead of GetProperty().

I would also note that reflection is an expensive operation, and a solution using a dictionary or switch would be much faster.

It’s not really an answer to your question but with your example shouldn’t you give references of your 3 lights to your Switch script? This way it can set the lights on and off immediately depending on its status.
You can use a table to put how many lights as you want in your switch.

Not exactly for sure how this would be done without putting my thinking hat on but as a quick alternative you could call a function on the Lights script from the Switch script passing the correct string ex. “red” then in that function use a switch statement to set the correct Boolean value to true…
//Lights Script

public void SetLights(String myString) 
{
      switch(myString)
      {
            case "red":
                      redlight = true;
                      break;
            case "blue":
                      bluelight = true;
                      break;
            case "yellow":
                      yellowlight = true;
                      break;
      }
}


//Switch Script

if (whatever)
{
      Lights.SetLights("red");
}
if(whatever)
{
     Lights.SetLights("blue");
}
etc.