Syntax
C#.Net
for (initializer; condition; iterator)
{
Body
}
VB.Net
For initializer = condition
Body
Next
Examples
Simple numeric for loop
C#.Net
for (int i = 0; i < 5; i++)
{
Console.WriteLine($"Index: {i}");
}
VB.Net
For i = 0 To 4
Console.WriteLine($"Index: {i}")
Next
In above code I have displayed the index value with the help of for loop. Here I have defined a variable and assign a value. After that condition have been applied that when loop will break.
Access an array with index access
C#.Net
int[] numbers = { 10, 20, 30, 40 };
for (int i = 0; i < numbers.Length; i++)
{
Console.WriteLine($"numbers[{i}] = {numbers[i]}");
}
VB.Net
Dim numbers = {10, 20, 30, 40}
For i = 0 To numbers.Length - 1
Console.WriteLine($"numbers[{i}] = {numbers(i)}")
Next
In above code I have declared an array and added some values. Now used for loop to get the array value by using index.Accessing a List<EmployeeDetail> using for
C#.Net
var employees = new List<EmployeeDetail>
{
new EmployeeDetail { EmpId = 1, EmpName = "Emp 1", Project = "P1" },
new EmployeeDetail { EmpId = 2, EmpName = "Emp 2", Project = "P2" },
new EmployeeDetail { EmpId = 3, EmpName = "Emp 3", Project = "P3" }
};
for (int i = 0; i < employees.Count; i++)
{
var e = employees[i];
Console.WriteLine($"{i}: {e.EmpId} - {e.EmpName} ({e.Project})");
}
VB.Net
Dim employees = New List(Of EmployeeDetail) From {
New EmployeeDetail With {.EmpId = 1,.EmpName = "Emp 1",.Project = "P1"},
New EmployeeDetail With {.EmpId = 2,.EmpName = "Emp 2",.Project = "P2"},
New EmployeeDetail With {.EmpId = 3,.EmpName = "Emp 3",.Project = "P3"}}
For i = 0 To employees.Count - 1
Dim e = employees(i)
Console.WriteLine($"{i}: {e.EmpId} - {e.EmpName} ({e.Project})")
Next
End Sub
In above code I have taken a class of employee and in this I have added employee detail. With the help of for loop I have displayed the employee detail.
Using continue and break
C#.Net
for (int i = 0; i < 10; i++)
{
if (i % 2 == 0) continue; // skip even numbers
if (i > 7) break; // stop when greater than 7
Console.WriteLine($"odd: {i}");
}
VB.Net
For i = 0 To 9
If i Mod 2 = 0 Then Continue For ' skip even numbers
If i > 7 Then Exit For ' stop when greater than 7
Console.WriteLine($"odd: {i}")
Next
In above code i have explained how you can use continue and break in for loop. Here we are displaying the odd value and use break is if it is an even value.



