2

Let's say I have a model:

public class MyModel 
{
    public int MyProperty { get; set; }
}

Than I have a Func pointing to MyProperty:

Func<MyModel, int> func = x => x.MyProperty;

So, using this func I would like to change my property on initialized object:

var myModel = new MyModel();
?????
Andrzej
  • 848
  • 1
  • 11
  • 26
  • What would be the role of `func`? Do you want to use it to point to the chosen property or use it as the actual setter? – haim770 Jul 09 '18 at 10:44
  • Do you only have a `Func<,>`, or could you potentially re-engineer to an `Expression>`? – Rawling Jul 09 '18 at 10:51
  • 1
    I want it to be a pointer. I can re-engineer to Expression. – Andrzej Jul 09 '18 at 10:51
  • @Rawling could you also provide example, how to achieve it with Expression>? – Andrzej Jul 14 '18 at 07:58
  • @Andrzej something like [this](https://stackoverflow.com/a/8111631/215380) (assumes you have a model called `instanceEntity` to set the value on.) – Rawling Jul 16 '18 at 06:54

1 Answers1

2

You need to pass the new value for "MyProperty" as an argument to your Func

    Func<MyModel,int, int> func = (x, newValue) => 
    {
        x.MyProperty = newValue;
        return newValue;
    };

And use it like this:

    var m = new MyModel();
    func(m, 2);

Alternatively, if you are not interested in the return value you can turn the Func into and Action:

Action<MyModel,int> func = (x, newValue) => x.MyProperty = newValue;

Also, you can capture the "MyModel" variable in a closure so that you don't pass the instance explicitly every time you want to change "MyProperty"'s value:

var myModel = new MyModel();    

Func<MyModel, Action<int>> getSetter = x => 
  newValue=>x.MyProperty = newValue;

var setter = getSetter(myModel);

setter(3);
setter(4);