Is there a way to refer to a property name with a variable?
Scenario: Object A have public integer property X an Z, so...
public void setProperty(int index, int value)
{
string property = "";
if (index == 1)
{
// set the property X with 'value'
property = "X";
}
else
{
// set the property Z with 'value'
property = "Z";
}
A.{property} = value;
}
This is a silly example so please believe, I have an use for this.
Easy:
a.GetType().GetProperty("X").SetValue(a, value);
Note that GetProperty("X")
returns null
if type of a
has no property named "X".
To set property in the syntax you have provided just write an extension method:
public static class Extensions
{
public static void SetProperty(this object obj, string propertyName, object value)
{
var propertyInfo = obj.GetType().GetProperty(propertyName);
if (propertyInfo == null) return;
propertyInfo.SetValue(obj, value);
}
}
And use it like this:
a.SetProperty(propertyName, value);
UPD
Note that this reflection-based method is relatively slow. For better performance use dynamic code generation or expression trees. There are good libraries that can do this complex stuff for you. For example, FastMember.
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