Tom
Tom

Reputation: 245

How to convert a string to code? (C#)

Is it possible to convert a string to code?
For example, instead of:

string foo = "bar";
...
switch(foo){
case "bar":
    pictureBox.Image = Project.Properties.Resources.bar;
    break;
...
}

Is there a way to simply:

string foo = "bar"
pictureBox.Image = Project.Properties.Resources.<foo string goes in here>;

I hope this example makes sense.

Upvotes: 2

Views: 208

Answers (1)

Julian J. Tejera
Julian J. Tejera

Reputation: 1021

What you are trying to do is called Reflection in C#. You can find a post in StackOverflow with code samples for it: Get property value from string using reflection in C#

EDIT: Here is the example

     string foo = "bar";
     var resources = Project.Properties.Resources;
     object o = resources.GetType().GetProperty(foo).GetValue(resources, null);
     if (o is System.Drawing.Image) {
            pictureBox.Image = (System.Drawing.Image) o;
     }

Upvotes: 4

Related Questions