I think there is a way to solve it if you relax requirement - have array of entities that would allow modifying set of local int
variables via operations on array.
To do so it is possible to capture references to the variables in an array of delegates that each take ref int val
.
void Increase(ref int x)
{
x++;
}
void Set(ref int x, int amount)
{
x = amount;
}
void Sample()
{
int a = 10;
int b = 20;
// Array of "increase variable" delegates
var increaseElements = new Action[] {
() => Increase(ref a),
() => Increase(ref b)
};
increaseElements[0](); // call delegate, unfortunately () instead of ++
Console.WriteLine(a); // writes 11
// And now with array of "set the variable" delegates:
var setElements = new Action<int>[] {
v => Set(ref a,v),
v => Set(ref b,v)
};
setElements[0](3);
Console.WriteLine(a); // writes 3
}
Notes
- directly using delegates you have to call them with ().
- it may be possible to fix
()
instead of ++
issue by wrapping delegate into an object that will call Increase as its ++
implementation....
- Issue with
Set
version where one need to call (3)
instead of = 3
will require more trickery - implementing custom class with indexing to redirect set [index]
to call saved setter function.
Warning: This is really done for entertainment purposes - please don't try it in real code.