Reputation: 21475
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.
Upvotes: 8
Views: 31285
Reputation: 21034
I think you mean reflection:
PropertyInfo info = myObject.GetType().GetProperty("NameOfProperty");
info.SetValue(myObject, myValue);
Upvotes: 5
Reputation: 9224
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.
Upvotes: 33
Reputation: 2654
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);
}
Upvotes: 0
Reputation: 82136
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);
Upvotes: 4