Re: foreach doesn't work with array of bools?
From: Adam Clauss (cabadam_at_tamu.edu)
Date: 08/04/04
- Next message: Patty O'Dors: "ReadOnly folder?"
- Previous message: Nodir Gulyamov: "Re: Microsoft Asyncronous TCP Server Implementation Example Problem"
- In reply to: Joe Rattz: "foreach doesn't work with array of bools?"
- Next in thread: Joe Rattz: "Re: foreach doesn't work with array of bools?"
- Reply: Joe Rattz: "Re: foreach doesn't work with array of bools?"
- Reply: Jon Skeet [C# MVP]: "Re: foreach doesn't work with array of bools?"
- Messages sorted by: [ date ] [ thread ]
Date: Wed, 4 Aug 2004 11:27:21 -0500
I actually just discovered this today actually hehe..
What is happening is the variable declared in the foreach becomes readonly.
So, in the case of
foreach(bool bit in bits)
the variable bit CANNOT have its value changed. It can be read from, but not changed. Which is why:
for(int i = 0; i < bits.Length; i++)
works. On that example, the variable i only gets read from (to tell bits[] which index to use).
That make sense?
I believe in .net that all variables have a default value... but I come from a C++ background, so I don't completely trust it and I
tend to always initialize all my variables anyway.
--
Adam Clauss
cabadam@tamu.edu
"Joe Rattz" <joerattz@yahoo.com> wrote in message news:O1puCajeEHA.1424@tk2msftngp13.phx.gbl...
> Hmmm, I wrote the following code. I want an array of bools and I want to
> intialize them to false.
>
> bool[] bits = new bool[10];
> foreach(bool bit in bits)
> {
> bit = false;
> }
>
> The compiler complains on the "bit = false;" stating that bit is read-only.
> If I iterate using an index though, it compiles just fine:
>
> for(int i = 0; i < bits.Length; i++)
> {
> bits[i] = false;
> }
>
> That compiles just fine. What is going on?
>
> Also, the array of bools seems to have intialized to false anyway. Can I
> count on that? Should I even worry about initializing them?
>
> Thanks.
>
>
- Next message: Patty O'Dors: "ReadOnly folder?"
- Previous message: Nodir Gulyamov: "Re: Microsoft Asyncronous TCP Server Implementation Example Problem"
- In reply to: Joe Rattz: "foreach doesn't work with array of bools?"
- Next in thread: Joe Rattz: "Re: foreach doesn't work with array of bools?"
- Reply: Joe Rattz: "Re: foreach doesn't work with array of bools?"
- Reply: Jon Skeet [C# MVP]: "Re: foreach doesn't work with array of bools?"
- Messages sorted by: [ date ] [ thread ]
Relevant Pages
|
Loading