Common C# Operators


Common C# Operators

Type Operator Function Example
Arithmetic + Add x = 1 + 2;
Subtract x = 1 – 2;
* Multiply x = 1 * 2;
/ Divide x = 1 / 2;
% Modulus (returns the remainder after division) x = 5 % 2;
returns 1 (5 divided by 2 gives a remainder of 1)
String Concatenation + String concatenation string str = “Hello ” + “World”;
Increment/decrement
If prefixed, the variable will be modified then used (also known as pre-increment or pre-decrement.)
If post-fixed, the variable will be used and then modified (also known as post-increment or post-decrement.)
++ Increment int x = 5;
int y = x++;
// value of y is 5
// value of x is 6
Decrement int x = 5;
int z = –x;
// value of z is 4
// value of x is 4
Relational (comparative)
Use these operators to construct true/false tests.
== Equal to 1 == 1 would return true (1 is equal to 1)
!= Not equal to 1 != 1 would return false
1 != 2 would return true (1 is not equal to 2)
< Less than 1 < 2 would return true (1 is less than to 2)
> Greater than 2 > 1 would return true (2 is greater than to 1)
<= Less than or equal to 1 <= 1 would return true (1 is equal to 1)
>= Greater than or equal to 1 >= 1 would return true (1 is equal to 1)
Logical
Use these operators in conditional blocks to test a condition statement.
&& Conditional and true && true would return true (both of the expressions are true)
|| Conditional or true || false would return true (one of the two expressions is true)
true Used only when a user-defined type overloads the logical operators. To gain short-circuiting capabilities for the class, the user needs to overload both operator true and operator false. Invoked only by the runtime.
false Used only when a user-defined type overloads the logical operators. To gain short-circuiting capabilities for the class, the user needs to overload both operator true and operator false. Invoked only by the runtime.
Assignment
These operators perform the operation between the left operand and the right operand and store the return value in the left operand.
+= Add and assign int x = 5;
x += 100;
// value of x is 105;
-= Subtract and assign int x = 5;
x -= 100;
// value of x is 95;
*= Multiply and assign int x = 5;
x *= 100;
// value of x is 500;
/= Divide and assign int x = 100;
x /= 100;
// value of x is 20;
%= Modulus and assign int x = 5;
x %= 100;
// value of x is 0;

Leave a comment

Filed under Sharing Stuff

Comment on this

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s