I have a class with lets say 5 Properties
Int32 Property1;
Int32 Property2;
Int32 Property3;
Int32 Property4;
Int32 Property5;
Now I have to set the values of only 3 three of those properties dynamically. so far is OK but my issue is I get those three property Names as strings on runtime. Lets say, something like this..
List<String> GetPropertiesListToBeSet()
{
List<String> returnList = new List<String>();
returnList.Add("Property1");
returnList.Add("Property3");
returnList.Add("Property4");
retun returnList;
}
So Now,
List<String> valuesList = GetPropertiesToBeSet();
foreach (String valueToSet in valuesList)
{
// How Do I match these Strings with the property Names to set values
Property1 = 1;
Property3 = 2;
Property4 = 3;
}
You can do something like this. Properties is your class
Properties p = new Properties();
Type tClass = p.GetType();
PropertyInfo[] pClass = tClass.GetProperties();
int value = 0; // or whatever value you want to set
foreach (var property in pClass)
{
property.SetValue(p, value++, null);
}
Let's say that the name of the class which contains them is Properties
. You can use the GetProperty()
method to get a PropertyInfo
and then the SetValue()
method:
Properties p = new Properties();
Type t = p.GetType(); //or use typeof(Properties)
int value = 1;
foreach (String valueToSet in valuesList) {
var bindingFlags = BindingFlags.NonPublic | BindingFlags.Instance; //because they're private properties
t.GetProperty(valueToSet, bindingFlags).SetValue(p, value++); //where p is the instance of your object
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With