↑ Grab this Headline Animator

Thursday, November 20, 2008

What is the difference between for and foreach loop in .net?

For Loop

  The For loop is the most popular loop. For loops enable us to execute a series of expressions multiple numbers of times. The For loop in VB .NET needs a loop index which counts the number of loop iterations as the loop executes.

The syntax for the For loop looks like this:

For index=start to end[Step step]
[Exit For]

  The index variable is set to start automatically when the loop starts. Each time in the loop, index is incremented by step and when index equals end, the loop ends.

Example on For loop

Module Module1

Sub Main()
Dim d As Integer
For d = 0 To 2
System.Console.WriteLine("In the For Loop")
Next d
End Sub

End Module

Foreach Loop
  Foreach loop takes object as variable and iteration will be happen. Suppose filling of the dropdown,dispaly the data into datagrid then we will prefer to use foreach loop. The foreach statement repeats a group of embedded statements for each element in an array or an object collection.

The syntax for the Foreach loop looks like this:

foreach((type)variable in objectcollection)
//piece of the code
for each (type)variable in objectcollection
//piece of the code
next object

In VB .NET, if the target object doesn't appear in the collection the For Each loop finishes with the looping variable pointing to the last item in the collection. That means this code always thinks it has found the target object.
[Actually most languages including VB say that the value of the looping variable is not defined at the end of the loop and that you should not rely on it having a particular value. That's certainly the case here.]

Here's one way around this problem.

Dim obj As Object
Dim found_it As Object

found_it = Nothing
For Each obj In values
If obj = txtValue.Text Then
found_it = obj
Exit For
End If
Next obj

If found_it Is Nothing Then
lblFoundIt.Text = "Not found"
lblFoundIt.Text = "Found"
End If

In VB 6, you can use code similar to the following to see if an object is in a collection.

For Each obj In values
If obj.value = target_value Then Exit For
Next obj

If obj Is Nothing Then
MsgBox "Not found"
MsgBox "Found"
End If

Foreach loop will consume more resource for operation as compared to for loop.

Submit this story to DotNetKicks

No comments:

Post a Comment

Post your comments/questions/feedback for this Article.


Latest Articles