Confused... "Cannot pass 'Item' as a ref or out argument because it is a 'foreach iteration variable

  • Thread starter Thread starter John Kelsey
  • Start date Start date
J

John Kelsey

I am an old, longtime C programmer surprised and confused by an error
message I'm getting from my VS2005 compiler...

"Cannot pass 'Item' as a ref or out argument because it is a 'foreach
iteration variable'" is the error message I'm getting for code that I think
should work. I'm sure that there is some sublety I'm missing... maybe with
the use of a reference, or foreach, or template class. Can someone maybe
explain it with small words or point me to something to read?

Example code:
using System;
using System.Collections.Generic;
namespace Test
{
class test
{
public int x = 1;
}

class Demo
{
List<test> BasicList = new List<test>();
public Demo()
{
BasicList.Add(new test());
foreach (test Item in BasicList)
{
Double(ref Item); // <---compiler error here
}
}
public void Double(ref test Item)
{
Item.x *= 2;
}
}
}

// In the old days, I'd use pointers and a for loop and it would work. Can
anyone help me sort it out in my head?
 
I am an old, longtime C programmer surprised and confused by an error
message I'm getting from my VS2005 compiler...

"Cannot pass 'Item' as a ref or out argument because it is a 'foreach
iteration variable'" is the error message I'm getting for code that I think
should work. I'm sure that there is some sublety I'm missing... maybe with
the use of a reference, or foreach, or template class. Can someone maybe
explain it with small words or point me to something to read?

"Foreach" variables are readonly, which means you can't pass them by
reference.

However, my guess is that you don't understand what "ref" really
means. See
http://pobox.com/~skeet/csharp/parameters.html

Jon
 
It's due to the way foreach works.
The reference Item is readonly so you can't have it point to a different
object.

On the other hand you don't need to use ref in the first place, since you're
working with a reference type already.

If you remove the ref keywords from your code it'll work as you expect it
to. (as long as what your expecting is for x to become 2 :-))
 
Back
Top