[Mono-devel-list] Basic C# help

Richard Norman normri at samc.com
Fri Dec 10 18:36:46 EST 2004


Your other option is to reverse your two statements... So that your
increment happens after to add it to the total... Like this...
 
>  int totalrevenue = 0;
>       user = 0;
>       while(user <= revenue.GetLength(0)) {
*>       totalrevenue += revenue[user];
*>       user ++;
>       }
The two  lines are switched and that should fix the out of bounds
error. Previously (as others already have stated) you increment before
you use the variable. You really want to use every entry (starting at
0).
 
You could also do a standard for loop which checks the length of the
array as the upper bound
 
for(user=0;user<revenue.Length; user++)
 
or you could do a foreach loop (it may not be the most efficient but it
could work)
 
foreach(float value1 in revenue)
 
Anyway, you have several ways to go through the loop. Just depends on
what you want to use. Just remember that ALL arrays are zero based
(first element is element 0)
 
Richard Norman
Web/Application Developer
 
http://www.jazzynupe.net/blog/
 
 
*****************************
Message: 12
Date: Fri, 10 Dec 2004 14:44:28 -0700
To: mono-devel-list at lists.ximian.com 
Subject: Re: [Mono-devel-list] Basic C# help
From: Phil Frost <indigo at bitglue.com>
 
On Fri, Dec 10, 2004 at 03:21:03PM -0600, Eric Scott wrote:
> Hey;
> I'm newbie to C#, and have been getting an error in some simple code
I'm 
> doing.  The error is right after the following while loop executes:
> 
>  int totalrevenue = 0;
>       user = 0;
>       while(user <= revenue.GetLength(0)) {
>       user ++;
>       totalrevenue += revenue[user];
>       }
> 
> Compiles fine, but when I run the exe file I get:
> 
> Unhandled Exception: System.IndexOutOfRangeException: Array index is
out 
> of range.
> in <0x00255> Test:Main (string[])
 
I don't know C# at all, but if I had to guess I'd say that the problem
is where you do "revenue[user]". I bet array indexes start at 0 and
thus
the largest valid index is one less than the size of the array. In
your
while loop you use "<=" where it should be "<", causing iteration to
continue exactly one cycle too long.
 

--__--__--

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.ximian.com/pipermail/mono-devel-list/attachments/20041210/b079e740/attachment.html 


More information about the Mono-devel-list mailing list