I think there is a way to solve the problem if you relax the requirement - to have an array of entities that will allow you to change the set of local variables int through operations on the array.
To do this, you can commit variable references to an array of delegates, each of which accepts 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 with the help of delegates you should call them with ().
- it is possible to fix
() instead of ++ , by delegating the delegate to an object that will call Increase as an implementation of ++ .... - The problem with the version of
Set , in which you need to call (3) instead of = 3 , will require more deception - implementing a custom class with indexing to redirect set [index] to call the saved setter function.
Warning: this is really for entertainment purposes - please do not try in real code.
source share