[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 226
  • Last Modified:

Is there a way to evaluate a string as code?

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?
0
bemara57
Asked:
bemara57
1 Solution
 
MisbahCommented:
I don't think there is an easier way to do that other than the way you already using now!
0
 
Jaime OlivaresSoftware ArchitectCommented:
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);
    }
}
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now