2

I have a simple class with 2 properties:

    class Circle {
protected int x = 0 {get; set;}
protected int y = 0 {get; set;} 
}

I have another class where the user can write which property he wants to change.

string selectProperty = Input.ReadString("Write which property to you want to change");  

In the same class I have a circle object, and I just want to change the value of a property according to his selection, to 5.

circle.selectProperty = 5;

This is just small example, I want to know the main idea, so 2 small "if"s won't help...
Thank you!

8
  • 1
    Try something like this: circle.GetType().GetProperty(selectProperty).SetValue(circle, 5) Commented Jan 10, 2017 at 11:12
  • what are you trying to achieve? Commented Jan 10, 2017 at 11:13
  • @Fabjan That's not working... any idea why? Commented Jan 10, 2017 at 11:19
  • @AmitKumarGhosh I'm trying to change a specific property that the user chose. Like an edit page. Commented Jan 10, 2017 at 11:20
  • @user7399016 One possible reason is that property's access modifier is protected, you can change it to public or use Bindingflags overload in GetProperty method. Commented Jan 10, 2017 at 11:22

1 Answer 1

2

I think you want to use reflection.

Circle circle = new Circle();
string selectProperty = Input.ReadString("Write which property to you want to change");
string selectedValue = Input.ReadString("Write which value should be written");
PropertyInfo propertyInfo = circle.GetType().GetProperty(selectedProperty);
propertyInfo.SetValue(circle, Convert.ChangeType(selectedValue, propertyInfo.PropertyType), null);

That should give you an idea.

Sign up to request clarification or add additional context in comments.

2 Comments

What's that PropertyInfo thing?
A class of the Reflection namespace which provides functionality to dynamically access properties of classes (in your case you are accessing properties by their name). Have a look at a .NET reflection tutorial. Basically you are able to access compiled objects at runtime which gives you great possibilities.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.