TheCreepySheep
TheCreepySheep

Reputation: 125

Adding value to integer in VB.NET

How do I add +1 value to an integer?

Something like

Do
    If myClientMachineIP.AddressFamily = Sockets.AddressFamily.InterNetwork Then
        Label2.Text = myClientMachineIP.ToString()
    Else
        TextBox2.Text = "IP is not equal to IPv4"
        proov = +1
        TextBox3.Text = proov
    End If
Loop Until proov = 10

How do I add +1 to the proov integer variable?

Upvotes: 3

Views: 26110

Answers (3)

Steven Liekens
Steven Liekens

Reputation: 14088

As is already suggested multiple times, simply adding 1 will usually suffice:

proov += 1

But it's worth knowing that this can get you in trouble once you start writing multithreaded applications, because incrementing a variable is not an atomic operation:

  1. Get the value from proov
  2. Increment this value by 1
  3. Store the new value in proov

If a thread y jumps in before thread x completes all 3 steps, thread x and y will end up doing the same thing.

To prevent that from happening, use the Interlocked class in the System.Threading namespace to Increment() the variable:

If myClientMachineIP.AddressFamily = Sockets.AddressFamily.InterNetwork Then
    Label2.Text = myClientMachineIP.ToString()
Else
    TextBox2.Text = "IP does not equal to IPv4"
    TextBox3.Text = Threading.Interlocked.Increment(proov)
End If

Upvotes: 2

Tim
Tim

Reputation: 28520

CORRECTION

VB.NET does not have the increment operator (++), so the simplest way would be to use the addition assignment operator += Operator:

proov += 1

Another way is to explicitly add 1 to the value:

proov = proov + 1

Upvotes: 7

bgs
bgs

Reputation: 3213

Simply try this:

proov++

or

TextBox2.Text = "IP does not equal to IPv4"
proov = proov + 1
TextBox3.Text = proov

Upvotes: 1

Related Questions