We help IT Professionals succeed at work.

Is there a way to evaluate a string as code?

bemara57
bemara57 asked
on
I have a class with properties like this:

SomeClass.PropertyA
SomeClass.PropertyB
SomeClass.PropertyC

I want to be able to pass a string to some method that evaluates the string input as code. Currently my method looks like this:

DoSomething(string selection)
{
    switch (section)
    {
        case "A":
            return SomeClass.PropertyA;
        case "B":
            return SomeClass.PropertyB;
        case "C":
            return SomeClass.PropertyC;
}

What I'm hoping to do is something like this:
DoSomething(string selection)
{
       return SomeClass.Property + selection;  //passing "A" would return SomeClass.PropertyA
}

Obviously this won't work, but I was trying to illustrate my intention. Is something like this possible?
Comment
Watch Question

MisbahSr. Software Engineer
CERTIFIED EXPERT

Commented:
I don't think there is an easier way to do that other than the way you already using now!
Software Architect
CERTIFIED EXPERT
Top Expert 2008
Commented:
you can do this with reflection, like:

public class SomeClass
{
   public object DoSomething(string selection)   // return type object, or change to a common type
   {
          PropertyInfo p = typeof(this).GetProperty("Property"+selection);  // change prefix "Property" if desired
          return p.GetValue(this, null);
    }
}

Explore More ContentExplore courses, solutions, and other research materials related to this topic.