The Basics - Arithmetic
Operators
The operators in Visual Basic .NET are ones that you should already be familiar with from school. They are:
- Addition: +
- Subtraction:-
- Multiplication:*
- Division:/
- Exponentation:^
The operators follow BODMAS or PEMDAS order of operations where parenthesis are calculated before exponents, exponents are calculated before multiplication and division, multiplication and division are calculated before addition and subtraction.
Return Types
It is important to consider the data type of the value that would be returned.
Take for example division operations. Since there is the possibility that division between two numbers can return a fraction (like 3 / 4) then the variable declared should be a numeric data type that can hold a decimal place (like a Double).
This isn't to say that all variables that may hold the result of some arithmetic operation should be declared as a Double, but it is to say that you should consider this beforehand.
Examples
The following demonstrates simple arithmetic operations:
Fiddle: Live Demo
Assignment Operators
While you should be familiar with the = assignment operator, there exists a different set assignment operators that act as shortcuts. They are:
- Addition: +=
- Subtraction:-=
- Multiplication:*=
- Division:/=
- Exponentation:^=
These operators allow for values to be equal to the result of their existing value and the desired operator on a value.
Examples
The following are some examples of assignment operators:
Fiddle: Live Demo
Remarks
In each assignment operator example the variable was assigned the existing value equal to itself and some mathematical operation. This type of assignment operator helps reduce the amount of code!