0
public class Test {
    public bool Case1 { get; set; }
    public bool Case2 { get; set; }
    public bool Case3 { get; set; }
}

Now if I get input as Case1 as string

public static void Main(String[] args) {
    string test = "Case1";
}

In this particular case if I get input as Case1, I need to assign value of Test.Case1 as true.

Igor
  • 60,821
  • 10
  • 100
  • 175
  • 1
    You could use a switch statement, or a set of if statements, or reflection. What have you tried and what is not working? – Igor Jun 30 '21 at 15:54
  • Related: [`GetProperty()` via reflection](https://stackoverflow.com/questions/1196991/get-property-value-from-string-using-reflection?rq=1). – D M Jun 30 '21 at 15:56
  • Thanks for the suggestion .I have used switch and if statements, since I have 13 fields to set depending on these values, I was looking for some reusable code. I will try reflection if that serves the purpose. Thanks. – Paritosh Tiwari Jun 30 '21 at 15:59

1 Answers1

0

If you want to use reflection, it would look something like this:

static void Main(string[] args)
{
    string test = "Case1";
    var myTest = new Test();
    var prop = myTest.GetType().GetProperty(test);
    prop.SetValue(myTest, true);
}

This is just a minimal example...in production code you'd want to have some error checking, for example to ensure that prop != null etc.

David784
  • 7,031
  • 2
  • 22
  • 29