The VB.NET For Loop – how to use it with tips & tricks in 2024

The VB.NET For Loop - how to use it with tips and tricks
The VB.NET For Loop – how to use it with tips and tricks

An essential part of VB.NET – the For Loop!

The For Loop is actually one of the most essential parts of VB.NET software development – this is exactly why I will demonstrate and explain the usage in today’s blogpost. Of course, it has an analog existence in the other .NET languages like C# as well and – more or less – just a different syntax. We will take a look at the differences and similarities in the corresponding sections of this post, but let’s start with the basics.

In short: The For Loop in VB.NET is an instruction block which loops (repeats) the inner contents (body) of the loop based on a counter. As an easy „what to use when“ reminder: Use a For Loop when you need to repeat things based on counting something and for example the „For Each Loop“ when your iterations are based on objects.

infoIf you need some quick and easy examples, I got you covered. Just navigate to the quick examples section of this blogpost.

You could say, that the „For Each Loop“ is some sort of counterpart to the „For Loop“, as it’s more „object based“ in comparison to some sort of counter oriented iteration. We will talk about tips and tricks further down below and like when or when not to use one or the other. Let’s now look at a typical real life example where you could perfectly use the For Loop in VB.NET – naturally this could be used in like C# as well.

What is the For Loop in VB.NET?

What is the For Loop in VB.NET?
What is the For Loop in VB.NET?

Imagine sitting at the table with your friends on a cozy evening while playing some cool card games like Uno. The game rounds are going well and like every Uno player on this planet, you understandably fear the famously infamous „draw 4 cards“ card. Your friend called Kevin then suddenly starts smiling at you as he drops the card you were feared of on you – even without any hesitation. Damn!

Being the fair and well behaved player you are, you of course start drawing those 4 cards calmly. At this point, your mind obviously starts to grow some payback vibes on Kevin in the background, but let’s not go too deep into that aspect. Let’s actually focus on the programming part of things here – like for example why you could perfectly use the VB.NET „For Loop“ here!

What actually happens behind the scenes

Take a look what actually happens behind the scenes (in your mind) when you hold onto the rules of the „draw 4 cards“ card. There are basically two important considerations when thinking about the situation which is analog to programming as well:

How the For Loop is structured in VB.NET and most other languages like CSharp
How the For Loop is structured in VB.NET and most other languages like C#

You could say „draw a card from the card deck, but 4 times“ where „draw a card“ is the actual instruction and the loop would then iterate 4 times. There’s another important factor as well, the „Block“ part. I mean, the corresponding programming language needs to know, where the developer actually started phrasing the „there will be a loop starting, now“.

As most things – according to secular laws – having a start, will also need to have an end. It’s the same in most of the programming languages! So the „here comes the loop“ block needs to end somewhere as well, otherwise the compiler wouldn’t be able to distinguish between: „Hey, this is a normal instruction“ and „Here comes a part of code I want to have executed multiple times – therefore, a loop“.

Take a look at the next section for VB.NET or .NET examples of the For Loop in general.

Quick For Loop examples in VB.NET

Quick examples of the For Loop in VB.NET and other .NET languages like C#
Quick examples of the For Loop in VB.NET and other .NET languages like C#

If you made it up to here, you’re most likely interested in some quick VB.NET For Loop example to like copy, paste and use. So let’s no longer waste time and get started! Keep in mind that you can switch between the code examples for both .NET languages – just to be complete.

Counting up like 1-5 with a For Loop

In the first little example I’m using the most typical version of a For Loop – just linear up-counting and outputting something to the console. Keep in mind, that you don’t need to explicitly define the „As Integer part“ – take a look at the second example:

' with an explicit "As Integer"
For i As Integer = 1 To 5
  Console.WriteLine($"Counting up: {i}")
Next

' without but implicitly working the same
For i = 0 To 5
  Console.Writeline($"Counting up: {i}")
Next

' Output (of both examples)
'Counting up 1
'Counting up 2
'Counting up 3
'Counting up 4
'Counting up 5
// with an explicit int declaration
for (int i = 1; i <= 5; i++) {
  Console.WriteLine($"Counting up: {i}");
}

' without but implicitly working the same
for (var i = 1; i <= 5; i++) {
  Console.WriteLine($"Counting up: {i}");
}

' Output (of both examples)
'Counting up 1
'Counting up 2
'Counting up 3
'Counting up 4
'Counting up 5

Counting down / reversed For Loop from 3-1

In this example I’m doing the opposite of counting up, I’m actually reversing the order / decrementing the count on each iteration. We will start at three and count down to one. Take a note of the „Step“ keyword used, this (in combination with the „amount“) enables us counting actually down. Of course you could use like „-2“ with fitting counter values as well:

For i As Integer = 3 To 1 Step -1
  Console.Writeline($"Counting down: {i}")
Next

' Output
'Counting down 3
'Counting down 2
'Counting down 1
for (int i = 3; i >= 1; i--) {
  Console.Writeline($"Counting down: {i}");
}

// Output
//Counting down 3
//Counting down 2
//Counting down 1

Only iterate even numbers

The next example shows how to only iterate even numbers. We can use the modulus operator for that. I declared an additional variable to make it as clear as possible, you could of course omit that one and put the boolean expression inside the „if check“ instead:

' only iterate even numbers
For i As Integer = 0 To 6
  Dim isEven = i Mod 2 = 0
  If isEven Then
    Console.WriteLine($"Next even number: {i}")
  End If
Next

' Output
'Next even number: 0
'Next even number: 2
'Next even number: 4
'Next even number: 6
// only iterate even numbers
for (int i = 0; i <= 6; i++) {
  bool isEven = i % 2 == 0;
  if (isEven) {
    Console.WriteLine($"Next even number: {i}");
  }
}

// Output
//Next even number: 0
//Next even number: 2
//Next even number: 4
//Next even number: 6

Iterate odd numbers only

This one is similar to the one from above, but with odd numbers instead of even ones:

' only iterate odd numbers
For i As Integer = 0 To 6
  Dim isOdd = i Mod 2 <> 0
  If isOdd Then
    Console.WriteLine($"Next odd number: {i}")
  End If
Next

' Output
'Next odd number: 1
'Next odd number: 3
'Next odd number: 5
// only iterate odd numbers
for (int i = 0; i <= 6; i++) {
  bool isOdd = i % 2 != 0;
  if (isOdd) {
    Console.WriteLine($"Next odd number: {i}");
  }
}

// Output
//Next odd number: 1
//Next odd number: 3
//Next odd number: 5

A For Loop based on dynamic input

Here’s an example where you could for example use dynamic input. No matter if it’s coming for example from a TextBox or from variables in general:

' uncomment A or B to make it work

'' A
' Dim fromValue = 1
' Dim toValue = 3

'' B
'' Of course you could need to take care
'' for wrong inputs with like Integer.TryParse
' Dim fromValue = Convert.ToInt32(TextBox1.Text)
' Dim toValue = Convert.ToInt32(TextBox2.Text)

For i As Integer = fromValue To toValue
  Console.WriteLine($"Iterating value {i}")
Next

' Output (for example - depending on TextBoxes input)
'Iterating value 1
'Iterating value 2
'Iterating value 3
// uncomment A or B to make it work

//// A
// int fromValue = 1;
// int toValue = 3;

//// B
//// Of course you could need to take care
//// for wrong inputs with like Integer.TryParse
// int fromValue = Convert.ToInt32(TextBox1.Text);
// int toValue = Convert.ToInt32(TextBox2.Text);

for (int i = fromValue; i <= toValue; i++) {
  Console.WriteLine($"Iterating value {i}");
}

// Output (for example - depending on TextBoxes input)
//Iterating value 1
//Iterating value 2
//Iterating value 3

An object based approach but with a counter

Now we’re doing something different! Even though we are using objects as a source, we can still use the For Loop to get our items. This will have the advantage of having something a numbering while iterating objects.

Public Class Card
  
  ' just an example class without stuff

End Class

' somewhere executable
' could use a For Loop to fill like a deck of cards, too
Dim cards = New List(Of Card)() From {
  New Card(),
  New Card(),
  New Card(),
  New Card()
}
For i As Integer = 1 To 3
  ' get a reference to the corresponding card
  Dim nr = i + 1
  Dim card = cards(i)
  Console.WriteLine($"Drawing card number: {nr}")
Next

' Output
'Drawing card number: 1
'Drawing card number: 2
'Drawing card number: 3
public class Card
{
  
  // just an example class without stuff

}

' somewhere executable
' could use a For Loop to fill like a deck of cards, too
List<Card> cards = new List<Card>()
{
  new Card(),
  new Card(),
  new Card(),
  new Card()
}
for (int i = i; i <= 3; i++) {
  // get a reference to the corresponding card
  int nr = i + 1;
  Card card = cards[i];
  Console.WriteLine($"Drawing card number: {nr}");
}

// Output
//Drawing card number: 1
//Drawing card number: 2
//Drawing card number: 3

warningIf you’ve seen the above example, you might be tempted to do something with „IndexOf“ to get the number of the card. For the sake of clean programming and effectiveness: DON’T do that! Please take a look at the next example!

' code from the previous example ...
' you might be tempted to do this

' BADE CODE - DON'T USE!!
For Each card In cards
  ' ------- DON'T DO THIS - see explanation below
  Dim nr = cards.IndexOf(card) + 1
  ' -------
  ' do something with the card variable..
  Console.WriteLine($"Drawing card number: {nr}")
Next
// code from the previous example ...
// you might be tempted to do this

// BADE CODE - DON'T USE!!
foreach (Card card in cards) {
  // ------- DON'T DO THIS - see explanation below
  int nr = cards.IndexOf(card) + 1;
  // -------
  // do something with the card variable..
  Console.WriteLine($"Drawing card number: {nr}");
}

If you take a look at the example from above, you could think of using it / doing it that way, but please, DON’T! Why not, you’re asking? Because you would tell the could to search through the whole card stack on each iteration. This means: For every card you are iterating, there’s another iteration of the whole stack, because it’s looking for the card you’re passing to „IndexOf“ inside the whole List.

Wrapping up

Wrapping up – The VB.NET For Loop
Wrapping up – The VB.NET For Loop

So in today’s post we’ve talked about the For Loop in VB.NET whose examples were also pretty applicable in C#, too. We talked about how loops kinda work in general and how we construct those loops. Then we took a look at different looping techniques like counting up, counting down (reverse) and iterating even or odd numbers.

One of the critical examples was looping over an object based list while keeping something like a counter as in „I’m currently looping object number x“. Don’t forget to avoid performance mistakes like the one shown here, when constructing For Loops in VB.NET. Thanks for reading and your time, see you soon!

Related posts

Here are some other posts you might be interest in. Feel free to take a look, I would be happy :)!

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert