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(in
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.
It's hard for me to understand what you're trying to achieve... if you're trying to determine the property and value separately, and at different times, you can wrap the act of setting the property inside a delegate.
public void setProperty(int index, int value)
{
Action<int> setValue;
if (index == 1)
{
// set property X
setValue = x => A.X = x;
}
else
{
// set property Z
setValue = z => A.Z = z;
}
setValue(value);
}
Not in the way your suggesting, but yes it is doable. You could use a dynamic
object (or even just an object with a property indexer) e.g.
string property = index == 1 ? "X" : "Z";
A[property] = value;
Or alternatively by using Reflection:
string property = index == 1 ? "X" : "Z";
return A.GetType().GetProperty(property).SetValue(A, value);
I think you mean reflection:
PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
info.SetValue(myObject, myValue);