Bartek Wójcik Bartek Wójcik - 1 month ago 14
C# Question

Changing object property while storing it in list

lets say i have class with a lot of redundant properties and i want to store them in list, dictionary or whatever

public class Foo
{
public Bar Bar1 {get;set;}
public Bar Bar2 {get;set;}
public Bar Bar3 {get;set;}
public Buzz Buzz1 {get;set;}
public Buzz Buzz2 {get;set;}
public Buzz Buzz3 {get;set;}


public void UpdateObject(Buzz newValue)
{
var dict = new List<KeyValuePair<Bar, Func<Buzz >>>()
{
new KeyValuePair<Bar, Func<Buzz>>(this.Bar1 ,()=>this.Buzz1),
new KeyValuePair<Bar, Func<Buzz>>(this.Bar2 ,() => this.Buzz2 ),
new KeyValuePair<Bar, Func<Buzz>>(this.Bar3 ,() => this.Buzz3 )
};

foreach (var item in dict)
{
if (true)
{
var value = item.Value.Invoke();
value = newValue;
}
}
}

}


of course
value
is changed but Foo's Buzz1/2/3 property is not. How can i store some kind of reference to object's property in list, get this item and change object's value?

Answer

Instead of the key value pairs with a key and a setter, store a key, a getter, and a setter:

List<Tuple<Bar, Func<Buzz>, Action<Buzz>>

Action<Buzz> is a lambda that takes a new value for that Buzz as a parameter.

var dict = new List<Tuple<Bar, Func<Buzz>, Action<Buzz>>
   {
        new Tuple<Bar, Func<Buzz>, Action<Buzz>(this.Bar1 ,()=>this.Buzz1, x => this.Buzz1 = x),
        // ...etc...
   };

Not sure why you're doing this, but that'll work.

If it were me, instead of a Tuple or KeyValuePair, I'd write a ThingReference<T> class that takes the two lambdas, and store those in a Dictionary<Bar, ThingReference<Buzz>>.