Re: foreach doesn't work with array of bools?

From: Adam Clauss (cabadam_at_tamu.edu)
Date: 08/04/04


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.
>
>


Relevant Pages

  • foreach doesnt work with array of bools?
    ... intialize them to false. ... That compiles just fine. ... the array of bools seems to have intialized to false anyway. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: foreach doesnt work with array of bools?
    ... I want an array of bools and I want to ... > intialize them to false. ... > That compiles just fine. ... the array of bools seems to have intialized to false anyway. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: foreach doesnt work with array of bools?
    ... > intialize them to false. ... the array of bools seems to have intialized to false anyway. ... The default value for a constructed bool is 'false': ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Fastcode CharPosRev B&V 0.1.0
    ... Our two first functions are array based because the treat the string as an ... array and indexes into it ... This compiles into ... CharNo: Integer; ...
    (borland.public.delphi.language.basm)
  • Re: Newbie questions
    ... It compiles ... float getLowest(float array, int length); ... float getLowest(float array[], int length) { ... before printing a second prompt. ...
    (comp.lang.c)

Loading