Answers for "foreach vs for c#"

C#
1

c# for vs foreach

// A normal For loop looks like this:
// For loop
int length = 100;  
for (int index = 1; index < length; index++)  
{  
	// Your code will be here 
}

// Exapmle between for loop and foreach loop:
// For loop
List<JCEmployee> JCEmployees = GetJCEmployeesList();  
for (int index = 0; index < JCEmployees.Count; index++)  
{  
	Console.WriteLine(JCEmployees[index].Age);  
}

// Foreach loop
List<JCEmployee> JCEmployees = GetJCEmployeesList();  
foreach(JCEmployee Employee in JCEmployees)  
{  
    Console.WriteLine(item.Age);              
}
Posted by: Guest on September-06-2021
1

for vs foreach loop

1-
  For Loop:
-It is flexible to iterate array
both ascending and descending order.
  For Each:
-It iterates from initial to end

2-
  For Loop:
-It runs until given condition become false
  For Each: 
-Keeps execution until last element
get executed

3-
  For Loop:
-It use index
  For Each:
-It use iteration

4-
  For Loop:
-Accepts both object collections and non object collections
  For Each:
-Accepts only object collections
Posted by: Guest on January-08-2021

C# Answers by Framework

Browse Popular Code Answers by Language