Arithmetic Operators

Arithmetic operators perform mathematical operations on numeric operands.

Overview

VB.NET provides a set of standard arithmetic operators that you can use to perform calculations. These operators work on various numeric data types such as Integer, Long, Single, Double, and Decimal.

Operator Description Example
+ Addition Dim sum As Integer = 5 + 3 ' sum = 8
- Subtraction Dim difference As Integer = 10 - 4 ' difference = 6
* Multiplication Dim product As Integer = 6 * 7 ' product = 42
/ Floating-point Division Dim result As Double = 10.0 / 4.0 ' result = 2.5
\ Integer Division Dim quotient As Integer = 10 \ 4 ' quotient = 2
Mod Modulo (Remainder of Division) Dim remainder As Integer = 10 Mod 3 ' remainder = 1
^ Exponentiation Dim power As Double = 2.0 ^ 3.0 ' power = 8.0

Division Operators

VB.NET offers two division operators, each with distinct behavior:

Example:


' Floating-point division
Dim floatResult As Double = 15.5 / 4.0
' floatResult will be 3.875

' Integer division
Dim intResult As Integer = 15 \ 4
' intResult will be 3

' Integer division with floating-point operands
Dim intResultFromFloat As Integer = CInt(15.5 \ 4.0)
' intResultFromFloat will be 3
            

Modulo Operator

The Mod operator returns the remainder of an integer division. This is useful for tasks such as determining if a number is even or odd, or for cycling through a range of values.

Example:


Dim number As Integer = 17
Dim divisor As Integer = 5

Dim remainder As Integer = number Mod divisor
' remainder will be 2 (because 17 = 3 * 5 + 2)

' Checking for even/odd
If number Mod 2 = 0 Then
    Console.WriteLine($"{number} is even.")
Else
    Console.WriteLine($"{number} is odd.")
End If
            

String Concatenation

While the + operator is primarily for arithmetic addition, it can also be used for string concatenation in VB.NET. However, the & operator is specifically designed for string concatenation and is often preferred for clarity.

Example:


Dim firstName As String = "Jane"
Dim lastName As String = "Doe"

' Using + for concatenation
Dim fullNamePlus As String = firstName + " " + lastName
' fullNamePlus will be "Jane Doe"

' Using & for concatenation (recommended)
Dim fullNameAmpersand As String = firstName & " " & lastName
' fullNameAmpersand will be "Jane Doe"

' Concatenating with other data types (implicitly converted to string)
Dim age As Integer = 30
Dim message As String = "My name is " & fullNameAmpersand & " and I am " & age.ToString() & " years old."
' message will be "My name is Jane Doe and I am 30 years old."