Revious
Revious

Reputation: 8146

Is it possible to make a method that sets the value of a Property which is passed to it as a parameter?

I would like to do something similar:

SetPropertyValue(ref class1.Sport, prop2);

private static void SetPropertyValue(ref Prop1 prop1, bool prop2)
{
    prop1 = new Prop1
    {
        BoolValue = prop2,
    };
}

Upvotes: 1

Views: 124

Answers (3)

Charlie
Charlie

Reputation: 9098

You can use Lambda Expressions and a method to call the setValue on the property.

Create this method:

public void SetPropertyValue<O, T>(O obj, Expression<Func<O, T>> property, T value)
{
    var memberSelectorExpression = property.Body as MemberExpression;
    if (memberSelectorExpression != null)
    {
        var p = memberSelectorExpression.Member as PropertyInfo;
        if (p != null)
        {
            p.SetValue(obj, value, null);
        }
    }
}

Then call it

SetPropertyValue(textBox1, (t=>t.BackColor), Color.Red );

See:

How to set property value using Expressions?

As Servy sugguests, performance may be an issue for you. You can also use a different technique described at CodeProject:

http://www.codeproject.com/Articles/584720/ExpressionplusbasedplusPropertyplusGettersplusandp

Upvotes: 3

BradleyDotNET
BradleyDotNET

Reputation: 61339

Since you already have a strong reference to the property, you shouldn't need to "dynamically" set it. All you need to do is:

class1.Sport = CreateProp1(prop2);

private Prop1 CreateProp1(bool initialBoolValue)
{
   return new Prop1()
   {
      BoolValue = initialBoolValue;
   }
}

Even better would be to modify Prop1 to have a constructor that takes a bool:

public Prop1(bool initialBoolValue)
{
   BoolValue = initialBoolValue;
}

class1.Sport = new Prop1(prop2);

Upvotes: 2

user2579857
user2579857

Reputation:

You can do it just like this:

class1.Sport = myProperty(property);

Upvotes: 0

Related Questions