-
July 8th, 2010, 03:16 PM
#1
List and Arrays
This might be a silly question but how do you properly compensate for List Counts and Array Size?
For example Lists and Array start at 0, but if I want to loop through them I need to -1 off the Count/Length or else I will get an out of bounds condition, is this a proper way of coding?
You can see my code below.
Code:
List<string> introMessage = new List<string>();
using (StreamReader introRead = new StreamReader("intro.txt"))
{
string line;
while ((line = introRead.ReadLine()) != null)
{
introMessage.Add(line);
}
}
for (int x = 0; x <= introMessage.Count-1; x++)
{
Console.WriteLine(introMessage[x]);
}
-
July 8th, 2010, 03:21 PM
#2
Re: List and Arrays
No, you are doing it wrong (well, maybe not wrong. It does work, it is just unconventional and unnecessary). You are using <=, when you need only use <.
Code:
for( int i = 0; i < someArray.Length; ++i )
{
// do stuff
}
However, arrays and generic collections implement IEnumerable, so just use a foreach statement instead:
Code:
foreach( int i in someArrayOfInts )
{
// do stuff
}
Last edited by BigEd781; July 8th, 2010 at 03:30 PM.
-
July 8th, 2010, 03:51 PM
#3
Re: List and Arrays
As Ed mentioned...
Code:
for (int x = 0; x < introMessage.Count; x++)
{
Console.WriteLine(introMessage[x]);
}
or using foreach...
Code:
foreach ( var line in introMessage )
{
Console.WriteLine( line );
}
In general, prefer using foreach over for.
-
July 8th, 2010, 04:17 PM
#4
Re: List and Arrays
I didn't know about foreach but I am definitely using that from now on.
Once again excellent responses from this forum.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|