foreach
This should be used when you have a collection.
If you are iterating through anything that is not a collection (for example an Array) it is more efficient to use a for loop.
Single Statement
When you only have a single statement the curly bracket is optional.
Example - System.Collections.ArrayList
ArrayList myArrayList = new System.Collections.ArrayList();
myArrayList.Add("one");
myArrayList.Add("two");
foreach (string element in myArrayList)
{
}
Example - System.Collections.Generic.List<int>
List<int> myNumbers = new System.Collections.Generic.List<int> { 1, 2, 3, 4, 5 };
foreach (int number in myNumbers)
{
Console.WriteLine(number);
}
© 2024 Better Solutions Limited. All Rights Reserved. © 2024 Better Solutions Limited TopPrevNext