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:
Note that
GetProperty("X")returnsnullif type ofahas no property named “X”.To set property in the syntax you have provided just write an extension method:
And use it like this:
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.