I'm trying to get clearer on limitations of assignment/modifications within
a foreach. Why does the following gives a compilation error if MyType is a
struct, but it does not if MyType is a class?
public struct MyType // change to class, and it compiles clean
{
public int f;
}
public void foo()
{
MyType[] a = new MyType[3];
for (int n = 0; n < 3; n++)
a[n] = new MyType();
foreach (MyType c in a)
{
c.f = 77; // compilation error: The left-hand side of assignment
must be a variable, property or indexer
this.WriteLine( c.f.ToString()) ;
}
} 5 2972
Brad,
I can't be sure without more investigation, but if a is an array of
reference types, what exactly is the variable c? It's a reference to an
instance of that type, and, duh, a reference to an instance that's in the
array you're iterating throught. So there shouldn't be any problem in
accessing a member of the instance by means of the reference. So what is c
if a is an array of value types? It's almost certainly a COPY of an instance
in the array. Even if this compiled, it probably wouldn't work, i.e., you'd
be assigning 77 to the f field of a copy, which is probably not what you
intended.
Tony
"Brad Williams" <br************ **@intel.com> wrote in message
news:c1******** **@news01.intel .com... I'm trying to get clearer on limitations of assignment/modifications
within a foreach. Why does the following gives a compilation error if MyType is
a struct, but it does not if MyType is a class?
public struct MyType // change to class, and it compiles clean { public int f; }
public void foo() { MyType[] a = new MyType[3];
for (int n = 0; n < 3; n++) a[n] = new MyType();
foreach (MyType c in a) { c.f = 77; // compilation error: The left-hand side of assignment must be a variable, property or indexer this.WriteLine( c.f.ToString()) ; } }
You could also create an array of System.Object, then (implicitly) box your
value types when you insert them, and explicitly cast them inside the
loop...no, that wouldn't work either, because you'd be unboxing a value into
a copy.
"Brad Williams" wrote... I'm trying to get clearer on limitations of assignment/modifications within a foreach. Why does the following gives a compilation error if MyType is a struct, but it does not if MyType is a class?
Because a struct is a value type, and those are "read-only" in a
foreach-loop (see below).
public struct MyType { public int f; }
public void foo() { MyType[] a = new MyType[3];
for (int n = 0; n < 3; n++) a[n] = new MyType();
foreach (MyType c in a) { c.f = 77; // compilation error: this.WriteLine( c.f.ToString()) ; } }
From the documentation:
foreach (type identifier in expression) statement
- identifier: The iteration variable that represents
the collection element. If the iteration variable
is a value type, it is effectively a read-only
variable that cannot be modified.
// Bjorn A
Good points all.
In either case, whether the type is struct or class, the foreach
element-instance variable is "read-only" according to the language spec, so
it comes down to how readonly affects struct variables versus class
variables. I guess it makes sense that a read-only struct variable *is* the
whole struct, thus all of its fields are read-only too. Whereas a read-only
class object's fields are not part of the class *variable*, so they don't
fall under the read-only-ness of the variable. As confirmation, readonly
acts this way in another test:
public class foo
{
public int x;
}
public struct bar
{
public int y;
}
public class quux
{
public readonly foo f = new foo();
public readonly bar b = new bar();
public void Test()
{
f.x = 1; // compiles
b.y = 2; // doesn't compile
}
}
Brad Williams
This is not allowed in C#, You cant modify with in a for-each loop.
From C# Lang specification (8.8.4) :
The foreach statement enumerates the elements of a collection,
executing an embedded statement for each element of the collection.
foreach-statement:
foreach ( type identifier in expression )
embedded-statement
The type and identifier of a foreach statement declare the iteration
variable of the statement. The iteration variable corresponds to a
read-only local variable with a scope that extends over the embedded
statement. During execution of a foreach statement, the iteration
variable represents the collection element for which an iteration is
currently being performed. A compile-time error occurs if the embedded
statement attempts to modify the iteration variable (via assignment or
the ++ and operators) or pass the iteration variable as a ref or
out parameter.
"Brad Williams" <br************ **@intel.com> wrote in message news:<c1******* ***@news01.inte l.com>... I'm trying to get clearer on limitations of assignment/modifications within a foreach. Why does the following gives a compilation error if MyType is a struct, but it does not if MyType is a class?
public struct MyType // change to class, and it compiles clean { public int f; }
public void foo() { MyType[] a = new MyType[3];
for (int n = 0; n < 3; n++) a[n] = new MyType();
foreach (MyType c in a) { c.f = 77; // compilation error: The left-hand side of assignment must be a variable, property or indexer this.WriteLine( c.f.ToString()) ; } } This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Edward Diener |
last post by:
Is there a way to override the default processing of the assignment operator
for one's own __value types ? I realize I can program my own Assign method,
and provide that for end-users of my class, but I would like to use
internally my own = operator for some of my value types, so I can say "x =
y;" rather than "x.Assign(y);".
The op_Assign operator seems impossibly broken since it takes __value copies
of the two objects. Perhaps there is...
|
by: Chris LaJoie |
last post by:
Our company has been developing a program in C# for some time now, and we
haven't had any problems with it, but just last night something cropped up
that has me, and everyone else, stumped.
I have a struct that contains several different types of data. This struct
is used throuout the program. Now, when I compile, I get 6 errors, all of
them "Use of possibly unassigned field 'awayTime'" or "Use of possibly
unassigned field 'intlTime'"....
|
by: Dan |
last post by:
hi newsgroup,
i need server side validation of user entries.
as i do have many fields, i would like to use reflection for checkinng
the IsValid property of all the Validators.
here is the reflection code
i don't understand why i get the following error:
Object does not match target type.
Description: An unhandled exception occurred during the execution of the
|
by: WJ |
last post by:
..Net Experts,
I have this concept described below:
1. I have a large (4K+) data record called Health_R. This record also
contains Text/memo fields and Image.
2. The record layout is below:
*******************
//My beloved c#
|
by: josh.23.french |
last post by:
Here's the code i have:
$db = array(); //main array
$db = array(); //table `main`
$db = array('id'=>0,
'username'=>'joshfrench','userpass'=>'password','userlevel'=>'admin');
//row
$db = array('id'=>1,
'username'=>'bob_smith','userpass'=>'psswrd','userlevel'=>'user');
//row
| |
by: TimeHorse |
last post by:
I would like to gauge interest in the following proposal:
Problem:
Assignment statements cannot be used as expressions.
Performing a list of mutually exclusive checks that require data
processing can cause excessive tabification. For example, consider
the following python snipet...
|
by: Rotsey |
last post by:
Hi,
I have a class that exist in my UI assembly that inherits from a class
in a referenced assembly like this.
class EmployeesDC
{
private string mstrEmployeeNumber;
etc
|
by: Maarten |
last post by:
I've found some answers to my problem on this forum, but not exactly the answer I was looking for. Sorry if I've missed something.
This is my situation:
I am trying to make an insertion into an MySQL table, using an array for the field list AND another array for the values. I know by know that you can't just use:INSERT INTO table_name ($array1) VALUES ($array2);
So i've stripped the arrays first. My problem however is that I can only...
|
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...
|
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...
|
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...
| |
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |