C# reference to loop variable


Is it possible in C# to something like the following

foreach (ref string var in arr) {
    var = "new value";

so that var variable was treated as reference and assigning to var would change an array element?

Best Solution

There is no such construct for updating a loop; an iterator is read-only. For example, the following provides a perfectly valid iterator:

public IEnumerable<int> Get1Thru5() {
    yield return 1; yield return 2; yield return 3;
    yield return 4; yield return 5;

How would it update? What would it update?

If the data is an array/list/etc, then something like:

for(int i = 0 ; i < arr.Length ; i++) {
    arr[i] = "new value";

Or other options depending on the specific container.

Update; at a push, an extension method:

public static void UpdateAll<T>(this IList<T> list, Func<T, T> operation) {
    for (int i = 0; i < list.Count; i++) {
        list[i] = operation(list[i]);
static void Main() {
    string[] arr = { "abc", "def", "ghi" };
    arr.UpdateAll(s => "new value");
    foreach (string s in arr) Console.WriteLine(s);