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?

-------------Problems Reply------------

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);
}

No. The foreach statement is simply syntax sugar on top of the IEnumerable interface. This interface defines a method to get en IEnumerator which in turn has methods to do read-only enumeration:

  • Current : object
  • MoveNext() : bool
  • Reset() : void

foreach(string s in strings)
{
Console.WriteLine(s);
}

is compiler shortcut for:

IEnumerator e = strings.GetEnumerator();
string s;
while(e.MoveNext())
{
s = e.Current;
Console.WriteLine(s);
}

Since IEnumerator.Current is a get-only property you can't set the value.

// Non-generic IEnumerator shown.
interface IEnumerator
{
bool MoveNext();
object Current { get; }
void Reset();
}

If you want to support an updatable enumerator you will need to create it yourself -- but you won't be able to use "foreach" with it, and you'll have to implement wrappers around all the common IEnumerable classes.

You'll have to analyze your current situation and figure out how to update. If you're using an IList interface you can do:

for(int i = 0; i < strings.Count; ++i)
{
string s = strings[i];
//do work
s = s.ToUpperInvariant();
strings[i] = s;
}

In the case of a string, no; C# strings are immutable (cannot be changed). If you were enumerating over objects of a different, mutable type, you can change the properties of those objects.

Just to illustrate what Jacob is talking about. Consider the code snippet below:

class MyInt
{
public int Val { get; set; }
public MyInt(int val) { this.Val = val; }
}

class Program
{
static void Main(string[] args)
{
MyInt[] array = new MyInt[] { new MyInt(1), new MyInt(2) };

foreach (var obj in array) Console.Write("{0}\t", obj.Val);

foreach (var obj in array)
{
obj = new MyInt(100); // This doesn't compile! the reference is read only
obj.Val *= 10; // This works just fine!
}

foreach (var obj in array) Console.Write("{0}\t", obj.Val);
}
}

Indeed, if you try to assign to the "obj" as above you'll get a compile time error. But nothing prevents you from modifying MyInt's properties through the "obj" reference

In the case of a string, no; C# strings are immutable (cannot be changed). If you were enumerating over objects of a different, mutable type, you can change the properties of those objects.

Category:c# Views:0 Time:2009-07-03
Tags: c# reference

Related post

  • What is an ideal variable naming convention for loop variables? 2008-09-19

    If you are writing a simple little loop, what should you name the counter? Provide example loops! --------------Solutions------------- 1) For normal old style small loops - i, j, k - If you need more than 3 level nested loops, this means that either

  • how can I create a reference to a variable in specman? 2009-06-29

    I have the following code in specman: var x := some.very.long.path.to.a.variable.in.another.struct; while (x == some_value) { //do something that uses x; //wait for something //get a new value for x x = some.very.long.path.to.a.variable.in.another.st

  • The $(this) in jQuery is not a loop variable? 2010-06-21

    The following put the id name of each div inside the div as content: <div id="divDiv"> </div> <div id="divLink"> </div> [...] $('div').each(function() { $(this).prepend($(this).attr('id')) }) will work but $('#divStatus div').

  • Perl - Push into arrays using variable references versus using variable copies 2010-10-10

    Question: Why can't I push elements into a 2d array that's inside of a while loop that parses through a SQL result set? I need some help here as to why this happens. The way data is stored into a 2d array can be done several ways, but for my purposes

  • Loop variable not getting collected 2011-05-24

    I have a loop variable that does not appear to be getting garbage collected (according to Red--Gate ANTS memory profiler) despite having gone out of scope. The code looks something like this: while (true) { var item = blockingQueue.dequeue(); // bloc

  • Defining anonymous functions in a loop including the looping variable? 2011-11-30

    I know that this code doesn't work and I also know why. However, I do not know how to fix it: JavaScript: var $ = function(id) { return document.getElementById(id); }; document.addEventListener('DOMContentLoaded', function() { for(var i = 1; i <=

  • Is there a Pythonic way to close over a loop variable? 2012-01-20

    I just ran across Eric Lippert's Closing over the loop variable considered harmful via SO, and, after experimenting, realized that the same problem exists (and is even harder to get around) in Python. >>> l = [] >>> for r in range(1

  • How can I reference a outside variable from within a function? 2012-02-12

    UPDATE: Sorry I was wrong with my assumption of the problem. Its due to me trying to make the function parallel and have multiple proceses change the same dictionary. How can I design my function so it allows for this? If I have to send the dictionar

  • Closing over the loop variable in Scala 2012-03-23

    As discussed in Eric Lippert's blog post Closing over the loop variable considered harmful, closing over the loop variable in C# can have unexpected consequences. I was trying to understand if the same "gotcha" applied to Scala. First of all, since t

  • Windows Batch Command : How to dereference FOR loop variable to check if that variable is SET in Environment Variable 2014-12-14

    I'm writing a batch command script where in there is a check for Environment variables. I need to write a FOR loop by passing all the required variables and then validate if it is defined or not and if it is not defined then prompt the value for that

  • Type limitation in loop variables in Java, C and C++ 2009-08-26

    Why Java, C and C++ (maybe other languages also) do not allow more than one type on for-loop variables? For example: for (int i = 0; i < 15; i++) in this case we have a loop variable i, which is the loop counter. But I may want to have another var

  • pylint: Using possibly undefined loop variable 'n' 2010-02-26

    Pylint say W: 6: Using possibly undefined loop variable 'n' with this code: iterator = (i*i for i in range(100) if i % 3 == 0) for n, i in enumerate(iterator): do_something(i) print n because if the iterator is empty (for example []) n is undefined,

  • In languages which create a new scope each time in a loop block, a new local copy of the local loop variable is created each time in that new scope? 2010-04-29

    It seems that in language like C, Java, and Ruby (as opposed to Javascript), a new scope is created for each iteration of a loop block, and the local variable defined for the loop is actually made into a local variable every single time and recorded

  • Missing $ on loop variable 2010-06-07

    1 #!/usr/bin/perl 2 use strict; 3 use warnings; 4 5 my @array = qw[a b c]; 6 foreach my($a,$b,$c) (@array) { 7 print "$a , $b , $c\n"; 8 } I receive following error: Missing $ on loop variable What is wrong? I am using: perl v5.10.1 (*) built for x86

  • Getting references to local variables created during eval() in JavaScript 2010-06-16

    In the scenario below, how can I get references to the variables declared during eval() if I do not know their names? function test() { eval("var myVariable = 5"); var locals = magic() // TODO What should we do here? alert(locals["myVariable"]); // r

  • From Eric Lippert's blog: "don't close over the loop variable" 2010-07-06

    Possible Duplicates: Why is it bad to use a iteration variable in a lambda expression C# - The foreach identifier and closures From Eric Lippert's 28 June 2010 entry: static IEnumerable<IEnumerable<T>> CartesianProduct<T>(this IEnum

  • Perl's foreach and changing the looping variable 2010-07-09

    I am writing a script in Perl and have a question about Perl's foreach construct. It appears that if you change one of the loop variables it changes in the actual array. Is this in fact the case, or have I done something completely wrong? I want to c

  • How to modify loop variable in ruby? 2010-07-26

    for i in (0..5) if(i==0) i=4 end puts i end In the above program I excepted the output as - 4 5 But instead it is - 4 1 2 3 4 5 So I conclude that loop variable isnt changing. How can change it? Can anyone tell me? Actually, In my program I need to s

  • Why is it so 'hard' to write a for-loop in C++ with 2 loop variables? 2010-08-09

    Possible Duplicate: In C++ why can’t I write a for() loop like this: for( int i = 1, double i2 = 0; … A C developer would write this: int myIndex; for (myIndex=0;myIndex<10;++myIndex) ... A C++ developer would write this to prevent the loop variab

Copyright (C) dskims.com, All Rights Reserved.

processed in 0.084 (s). 11 q(s)