What is the advantage
and disadvantage
of the two loops?
I don't know their deferrences
to each other
.
the truth is I don't know where will I use the for loop
or the foreach loop
.
What is the advantage
and disadvantage
of the two loops?
I don't know their deferrences
to each other
.
the truth is I don't know where will I use the for loop
or the foreach loop
.
If you are iterating over a collection which has enumerable properties then you can use foreach. For example:
foreach (var customer in customers)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
You could also achieve the same with a for loop:
for (var i = 0; i < customers.Count; i ++)
{
Console.WriteLine(customers[i].FirstName + " " + customers[i].LastName);
}
In this case the first is more readable and easier to code right?
If you want to do a loop for some other reason though such as not iterating over a collectio but doing something x times then maybe a for loop is better. Also a for loop gives you access to the number of iterations you are on. So if you want to output:
1 Dave Amour
2 Fred Bloggs
3 Sarah Smith
Then there may be a case for using a for loop - it's up to you to make that call though.
Note - in order to be able to use foreach then the collection you are iterating over must implement IEnumberable or IEumerable<T>. Almost all collections do.
Here is a console app you can tinker with.
using System;
using System.Collections.Generic;
namespace ForeachVerusForLoop
{
class Program
{
static void Main(string[] args)
{
var customers = GetCustomers();
foreach (var customer in customers)
{
Console.WriteLine(customer.FirstName + " " + customer.LastName);
}
for (var i = 0; i < customers.Count; i ++)
{
Console.WriteLine(customers[i].FirstName + " " + customers[i].LastName);
}
Console.ReadKey();
}
static List<Customer> GetCustomers()
{
var customers = new List<Customer>
{
new Customer { FirstName = "Dave", LastName = "Amour" },
new Customer { FirstName = "Fred", LastName = "Bloggs" },
new Customer { FirstName = "Sarah", LastName = "Smith" }
};
return customers;
}
}
class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
Thank you sir.
That's the info that I want.
In this case the first is more readable and easier to code right?
If all you need is read-only context, sure. Two cases where it's not easier is when you want to index of the enumerated item and when you want to replace the enumerated item. A foreach
loop isn't inherently conducive for either, and that's where a for
loop is simpler when iterating over a collection.
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.