C# - Operators
In C#, an operator is a symbol that represents a specific operation to be performed on one or more operands. It defines how the operands should be manipulated or compared to produce a result. Operators are an essential part of the language and are used extensively in expressions and statements.
Here are the different types of operators in C#:
1. Arithmetic Operators:
-
Addition (
+
): Adds two operands. -
Subtraction (
-
): We need this operator -
when we want to subtract the second operand from the first. -
Multiplication (
*
): Multiplies two operands. -
Division (
/
): The division operator /
is used to divide the first operand by the second. -
Modulus (
%
): Returns the remainder after division.
Here's an illustration of arithmetic operators in C# with examples:
int a = 10;
int b = 3;
int sum = a + b; // Addition operator
int difference = a - b; // Subtraction operator
int product = a * b; // Multiplication operator
int quotient = a / b; // Division operator
int remainder = a % b; // Modulus operator
Console.WriteLine($"Sum: {sum}"); // Output: Sum: 13
Console.WriteLine($"Difference: {difference}"); // Output: Difference: 7
Console.WriteLine($"Product: {product}"); // Output: Product: 30
Console.WriteLine($"Quotient: {quotient}"); // Output: Quotient: 3
Console.WriteLine($"Remainder: {remainder}"); // Output: Remainder: 1
In the above example, we have two variables 'a' and 'b' initialized with values 10 and 3, respectively. The arithmetic operators are then used to perform various operations on these variables:
-
The addition operator ('+') adds the values of 'a' and 'b', resulting in the sum of 13.
-
The subtraction operator ('-') subtracts the value of 'b' from 'a', resulting in the difference of 7.
-
The multiplication operator ('*') multiplies the values of 'a' and 'b', resulting in the product of 30.
-
The division operator ('/') divides the value of 'a' by 'b', resulting in the quotient of 3. Note that since both 'a' and 'b' are integers, the division operation yields an integer quotient, discarding the fractional part.
-
The modulus operator ('%') returns the remainder when 'a' is divided by 'b', resulting in the remainder of 1.
Each result is then printed to the console using Console.WriteLine()
.
These arithmetic operators allow you to perform basic mathematical calculations in C#, making it easy to manipulate numerical data.
2. Assignment Operators:
-
Assignment (
=
): Assigns a value to a variable.
-
Compound Assignment (e.g.,
+=
, -=
, *=
, /=
): Performs an operation and assigns the result to the variable.
Here's an example illustrating the use of the assignment operator in C#:
int a = 10;
int b;
b = a; // Assignment operator
Console.WriteLine($"Value of b: {b}"); // Output: Value of b: 10
In the above example, we have a variable a
initialized with a value of 10
. Then, the assignment operator (=
) is used to assign the value of a to another variable b
. After the assignment, the value of b
becomes 10
.
The assignment operator is used when our requirement is that we want to store a value into a variable. It takes the value on the right side and assigns it to the variable on the left side. In this case, the value of a
is assigned to b
.
The result is then printed to the console using Console.WriteLine()
.
Assignment operators are fundamental in C# for initializing variables, storing values, and updating variables with new values throughout the program.
3. Comparison Operators:
-
Equal to (
==
): Checks if two operands are equal. -
Not equal to (
!=
): Checks if two operands are not equal. -
Greater than (
>
): This operator is used to check if the first operand is greater than the second. -
Less than (
<
): Checks if the first operand is less than the second. -
Greater than or equal to (
>=
): Checks if the first operand is greater than or equal to the second. -
Less than or equal to (
<=
): Checks if the first operand is less than or equal to the second.
Here are the comparison operators in C# along with examples:
int a = 5;
int b = 3;
bool isEqual = (a == b); // Equal to operator
bool isNotEqual = (a != b); // Not equal to operator
bool isGreater = (a > b); // Greater than operator
bool isLess = (a < b); // Less than operator
bool isGreaterOrEqual = (a >= b); // Greater than or equal to operator
bool isLessOrEqual = (a <= b); // Less than or equal to operator
Console.WriteLine($"a == b: {isEqual}"); // Output: a == b: False
Console.WriteLine($"a != b: {isNotEqual}"); // Output: a != b: True
Console.WriteLine($"a > b: {isGreater}"); // Output: a > b: True
Console.WriteLine($"a < b: {isLess}"); // Output: a < b: False
Console.WriteLine($"a >= b: {isGreaterOrEqual}"); // Output: a >= b: True
Console.WriteLine($"a <= b: {isLessOrEqual}"); // Output: a <= b: False
In the above example, we have two variables a and b initialized with values 5
and 3
, respectively. The comparison operators are used to compare these variables:
-
The equal to operator (
==
) checks if a is equal to b and returns False. -
The not equal to operator (
!=
) checks if a is not equal to b and returns True. -
The greater than operator (
>
) checks if a is greater than b and returns True. -
The less than operator (
<
) checks if a is less than b and returns False. -
The greater than or equal to operator (
>=
) checks if a is greater than or equal to b and returns True. -
The less than or equal to operator (
<=
) checks if a is less than or equal to b and returns False.
Each result is then printed to the console using Console.WriteLine()
.
Comparison operators are used to compare values and determine relationships between them in conditions and decision-making processes in C# programming.
4. Logical Operators:
-
Logical AND (
&&
): Returns true if both operands are true. -
Logical OR (
||
): Returns true if at least one operand is true. -
Logical NOT (
!
): Negates the truth value of the operand.
Here are the logical operators in C# along with examples:
bool a = true;
bool b = false;
bool logicalAnd = a && b; // Logical AND operator
bool logicalOr = a || b; // Logical OR operator
bool logicalNot = !a; // Logical NOT operator
Console.WriteLine($"a && b: {logicalAnd}"); // Output: a && b: False
Console.WriteLine($"a || b: {logicalOr}"); // Output: a || b: True
Console.WriteLine($"!a: {logicalNot}"); // Output: !a: False
In the above example, we have two boolean variables a
and b
with values true
and false
, respectively. The logical operators are used to perform logical operations on these variables:
-
The logical AND operator (
&&
) checks if both 'a' and 'b' are 'true' and returns 'false'. -
The logical OR operator (
||
) checks if either 'a' or 'b' (or both) is true and returns 'true'. -
The logical NOT operator (
!
) negates the value of 'a' and returns 'false'.
Each result is then printed to the console using Console.WriteLine()
.
Logical operators are used to evaluate boolean expressions and make logical decisions based on the conditions in C# programming.
5. Bitwise Operators:
-
Bitwise AND (
&
): Performs a bitwise AND operation. -
Bitwise OR (
|
): Performs a bitwise OR operation. -
Bitwise XOR (
^
): Performs a bitwise exclusive OR operation. -
Bitwise NOT (
~
): Flips the bits of the operand. -
Left Shift (
<<
): Shifts the bits of the left operand to the left by the number of positions specified by the right operand. -
Right Shift (
>>
): Shifts the bits of the left operand to the right by the number of positions specified by the right operand.
Here are the bitwise operators in C# along with examples:
int a = 10; // Binary: 0000 1010
int b = 6; // Binary: 0000 0110
int bitwiseAnd = a & b; // Bitwise AND operator
int bitwiseOr = a | b; // Bitwise OR operator
int bitwiseXor = a ^ b; // Bitwise XOR (exclusive OR) operator
int bitwiseNotA = ~a; // Bitwise NOT (complement) operator on 'a'
int leftShift = a << 2; // Left shift operator on 'a'
int rightShift = a >> 2; // Right shift operator on 'a'
Console.WriteLine($"a & b: {bitwiseAnd}"); // Output: a & b: 2
Console.WriteLine($"a | b: {bitwiseOr}"); // Output: a | b: 14
Console.WriteLine($"a ^ b: {bitwiseXor}"); // Output: a ^ b: 12
Console.WriteLine($"~a: {bitwiseNotA}"); // Output: ~a: -11
Console.WriteLine($"a << 2: {leftShift}"); // Output: a << 2: 40
Console.WriteLine($"a >> 2: {rightShift}"); // Output: a >> 2: 2
In the above example, we have two integer variables a
and b
with values 10
and 6
, respectively. The bitwise operators are used to perform bitwise operations on these variables:
-
The bitwise AND operator ('&') performs a bitwise AND operation on the binary representations of 'a' and 'b', resulting in the value 2 (Binary: 0000 0010).
-
The bitwise OR operator ('|') performs a bitwise OR operation on the binary representations of 'a' and 'b', resulting in the value 14 (Binary: 0000 1110).
-
The bitwise XOR (exclusive OR) operator ('^') performs a bitwise XOR operation on the binary representations of 'a' and 'b', resulting in the value 12 (Binary: 0000 1100).
-
The bitwise NOT (complement) operator ('~') performs a bitwise NOT operation on the binary representation of 'a', resulting in the value -11 (Binary: 1111 0101) due to two's complement representation.
-
The left shift operator ('<<') shifts the bits of a to the left by 2 positions, resulting in the value 40 (Binary: 0010 1000).
-
The right shift operator ('>>') shifts the bits of 'a' to the right by 2 positions, resulting in the value 2 (Binary: 0000 0010).
Each result is then printed to the console using Console.WriteLine()
.
Bitwise operators are used to manipulate individual bits within binary representations of numbers in C# programming.
6. Conditional Operator:
-
Conditional (?): Evaluates a condition and returns one of two expressions based on the result.
Here's an example illustrating the use of the conditional operator (also known as the ternary operator) in C#:
int a = 10;
int b = 5;
int max = (a > b) ? a : b; // Conditional operator
Console.WriteLine($"Maximum value: {max}"); // Output: Maximum value: 10
In the above example, we have two variables a
and b
initialized with values 10 and 5, respectively. The conditional operator (? :) is used to assign the maximum value between a and b to the variable max.
The conditional operator takes three operands: a condition, an expression to be evaluated if the condition is true, and an expression to be evaluated if the condition is false. If the condition is true, the first expression (in this case, a) is evaluated and assigned to max. If the condition is false, the second expression (in this case, b) is evaluated and assigned to max.
In the example, since a
is greater than b
, the condition evaluates to true, and the value of a (which is 10
) is assigned to max
. Therefore, the output is "Maximum value: 10".
The conditional operator is a concise way to express conditional assignments or expressions in C#, making the code more readable and compact.
7. Membership Operator:
-
in: Checks if a value exists in a specified collection.
-
is: Checks if an object is of a specified type.
Here's an example demonstrating the use of the in operator in C#:
string[] colors = { "Red", "Green", "Blue" };
bool containsRed = "Red" in colors; // Membership check with 'in' operator
bool containsYellow = "Yellow" in colors; // Membership check with 'in' operator
Console.WriteLine($"Contains Red: {containsRed}"); // Output: Contains Red: True
Console.WriteLine($"Contains Yellow: {containsYellow}"); // Output: Contains Yellow: False
In the example above, we have an array of strings called colors
that contains different colors. We use the in
operator to check membership or containment of values within the array:
-
The expression "Red" in colors checks if the string "Red" is present in the colors array. It returns True because "Red" is indeed present in the array.
-
The expression "Yellow" in colors checks if the string "Yellow" is present in the colors array. It returns False because "Yellow" is not found in the array.
The results of the membership checks are then printed to the console using Console.WriteLine()
.
The in
operator is useful for checking if a specific value exists within an array, collection, or other types that support the containment check.
These are the main categories of operators in C#. Each category includes one or more specific operators that perform different operations on operands.