C# Operators
Operators are symbols that represent computations or operations on variables and values. C# supports a variety of operators, which can be categorized into the following types.
1. Arithmetic Operators
+
(Addition)
-
(Subtraction)
*
(Multiplication)
/
(Division)
%
(Modulus, returns the remainder of a division)
int a = 10;
int b = 3;
int result = a + b; // result = 13
2. Comparison Operators
==
(Equal to)
!=
(Not equal to)
<
(Less than)
>
(Greater than)
<=
(Less than or equal to)
>=
(Greater than or equal to)
int x = 5;
int y = 10;
bool isEqual = x == y; // isEqual = false
3. Logical Operators
&&
(Logical AND)
||
(Logical OR)
!
(Logical NOT)
bool condition1 = true;
bool condition2 = false;
bool result = condition1 && condition2; // result = false
4. Assignment Operators
=
(Assignment)
+=
(Addition assignment)
-=
(Subtraction assignment)
*=
(Multiplication assignment)
/=
(Division assignment)
%=
(Modulus assignment)
int num = 10;
num += 5; // num = num + 5, so num is now 15
5. Increment and Decrement Operators
++
(Increment by 1)
--
(Decrement by 1)
int count = 5;
count++; // count is now 6
6. Bitwise Operators
&
(Bitwise AND)
|
(Bitwise OR)
^
(Bitwise XOR)
~
(Bitwise NOT)
<<
(Left shift)
>>
(Right shift)
int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // result = 1 (binary: 0001)
7. Conditional Operator (Ternary Operator)
? :
(Conditional expression)
int value = (x > y) ? x : y; // if x > y, value = x; otherwise, value = y
These are the basic operators in C#. Understanding how to use them is fundamental for writing C# code.