C# Tutorials
C# Methods
C# Classes
C# Examples
Operators are used to perform functions on variables and values.
In the example below, we use + operator to add two values together:
int "x"
=
100
+
50
;
Although operator + is often used to add two values together, as in the example above, they can also be used to add variables and values, or variables and other variables:
int "sum1"
=
100
+
50
; // 150 (100 + 50)
int "sum2"
=
"sum1"
+
250
;
// 400 (150 + 250)
int "sum3"
=
"sum2"
+
"sum2"
;
// 800 (400 + 400)
Arithmetic operators used to perform basic mathematical operations:
Operator | Name | Description | Example |
---|---|---|---|
+ | Addition | Adds together two values | x + y |
- | Subtraction | Subtracts one value from another | x - y |
* | Multiplication | Multiplies two values | x * y |
/ | Division | Divides one value by another | x / y |
% | Modulus | Returns the division remainder | x % y |
++ | Increment | Increases the value of a variable by 1 | x++ |
-- | Decrement | Decreases the value of a variable by 1 | x-- |
Assignment operators are used to assign variable values.
In the example below, we use a assign operator (=) to assign a value to 10 of the variables called x:
int "x"
=
10
;
The addition assignment operator (+ =) adds value to the variant:
int "x"
=
10
;
"x"
+=
5
;
List of all assignment operators:
Operator | Example | Same As |
---|---|---|
= | x = 5 | x = 5 |
+= | x += 3 | x = x + 3 |
-= | x -= 3 | x = x - 3 |
*= | x *= 3 | x = x * 3 |
/= | x /= 3 | x = x / 3 |
%= | x %= 3 | x = x % 3 |
&= | x &= 3 | x = x & 3 |
|= | x |= 3 | x = x | 3 |
^= | x ^= 3 | x = x ^ 3 |
>>= | x >>= 3 | x = x >> 3 |
<<= | x <<= 3 | x = x << 3 |
Comparison operators are used to compare two values:
Operator | Name | Example |
---|---|---|
== | Equal to | x == y |
!= | Not equal | x != y |
> | Greater than | x > y |
< | Less than | x < y |
>= | Greater than or equal to | x >= y |
<= | Less than or equal to | x <= y |
Logical operators are used to determine the logic between variables or values:
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical and | Returns true if both statements are true | x < 5 && x < 10 |
|| | Logical or | Returns true if one of the statements is true | x < 5 || x < 4 |
! | Logical not | Reverse the result, returns false if the result is true | !(x < 5 && x < 10) |