Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refer to a property name by variable

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.

like image 737
DontVoteMeDown Avatar asked Nov 08 '12 15:11

DontVoteMeDown


1 Answers

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.

like image 92
tukaef Avatar answered Oct 01 '22 08:10

tukaef