473,772 Members | 2,442 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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

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.Collecti ons.Generic;
namespace Test
{
class test
{
public int x = 1;
}

class Demo
{
List<testBasicL ist = new List<test>();
public Demo()
{
BasicList.Add(n ew 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?
Aug 24 '07 #1
2 19904
On Aug 24, 3:34 pm, "John Kelsey" <kels...@tacits .comwrote:
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

Aug 24 '07 #2
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 :-))
"John Kelsey" <ke*****@tacits .comwrote in message
news:%2******** ********@TK2MSF TNGP02.phx.gbl. ..
>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.Collecti ons.Generic;
namespace Test
{
class test
{
public int x = 1;
}

class Demo
{
List<testBasicL ist = new List<test>();
public Demo()
{
BasicList.Add(n ew 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?
Aug 24 '07 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
7473
by: DraguVaso | last post by:
Hi, Something I don't understand about a Typed DataSet: When a value in the DataSet is DBNull, it throws this error: "Cannot get value because it is DBNull". But aren't Typed DataSets invented to make life easier, to be able to get to tge Tables and Values with less code, in less time? But with this thing you need to add a Try-Catch around every statement when using the value, add for each value a default value in your DataSet (and...
2
10650
by: Mr.KisS | last post by:
Hello. I'm under Windows XP PRO SP1, IIS 5.1 ans SQL SERVER 2005 Express. When i try to open a connexion with : <connectionStrings> <add name="AppCnxStr" connectionString="Server=KLEO\SQLEXPRESS;Integrated Security=True;Database=C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Data\wizou.mdf" providerName="System.Data.SqlClient" />
9
3520
by: Igor Okulist | last post by:
int func(void**); { short* p = NULL; func(&p); //<<< here } Could somebody remind me why is this not allowed ? error message: "cannot convert parameter from 'short **' to 'void **'"
2
4114
by: Florian G. Pflug | last post by:
Hi Since sometime yesterday, my postgresql (7.4.5) reports "ERROR: cannot compare arrays of different element types", when I analyze a specific table in my database. Here is the tables definition: Column | Type | Modifiers -------------------+------------------------+---------------------------------------------------- self | datagraph."GOLink" | not null default
0
1645
by: shengmin.ruan | last post by:
i got a struct like: --------------------- public ref struct OutPacket{ int m_replyIndex; List<MainInfo^>^ m_mainInfos; }; --------------------- when i pass it to another process, i have to transfer it to intptr :
0
1628
by: DongWook | last post by:
Dear all, I've a windows application with crystal viewer to show a report (using vb .net 2003). I made a setup project and installed on client machines (no .net and crystal report). The application works just fine till my client logon to domain then this error popup "Cannot find KeycodeV2.dll or invalid keycode " when trying to show report. I've read other topics about this issue, all said about missing merge module or license key but I...
2
22765
by: mahesh | last post by:
Can anyone direct me to the place where i find the solution for the error message "cannot call member function 'X' without object"??? thanks in advance
0
9454
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10264
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10106
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10039
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9914
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8937
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5355
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5484
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2851
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.