C# Operators
A symbol that tells the compiler to apply a particular logical or mathematical operation to one or more operands values or expressions is called an operator in C#. To create C# programs and work with variables and data, operators are essential building blocks. They generate a result after receiving operands as input.
The number of operands that C# operators accept can be used to classify them:
Unary operators: ++, –, new,!, ~ are examples of unary operators that only work on a Unary operators.
Binary operators: Two operands are subject to Binary operators (e.g., +, -, *, /, ==,!=).
Conditional operator: Three operands are needed for the only ternary operator, the conditional operator (?:).
A thorough examination of several C# operators is provided here, along with examples:
Arithmetic Operators
Arithmetic operators are used to carry out simple mathematical computations.
Addition (+): Utilised while working with numerical data types in mathematical addition. Additionally, it can be used with character or string data types to execute string concatenation, or appending.
- Example: 10 + 5 = 15
- Example:
string firstName = "John"; string lastName = "Doe"; string fullName = firstName + " " + lastName; Console.WriteLine(fullName); // John Doe.
Subtraction (-): Does subtraction in mathematics. 10 – 5 = 5, for instance.
Multiplication (*): Carries out multiplication maths. 10 * 5 = 50 is an example.
Division (/): The numerator is divided by the denominator.
- It does integer division on integer operands, truncating any remainder. The formula is
14 / 5 = 2
. - When it divides real numbers (like
float
anddouble
), it produces a number with a whole and a fractional portion. When dividing a real number by 0.0, the result is either +∞ (Infinity), -∞ (-Infinity), or NaN (invalid value). - Example::
double squareSide = 17 / 4.0; Console.WriteLine(squareSide); // 4.25.
Modulus (%): Gives back the remainder of a division by an integer. Use of this operator is limited to integer data types. For instance: 5% 2 = 1
.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulo | a % b (remainder of integer division) |
Example
using System;
namespace OperatorsAppl
{
class Program
{
static void Main(string[] args)
{
int a = 21;
int b = 10;
int c;
c = a + b;
Console.WriteLine("Line 1 - Value of c is {0}", c);
c = a - b;
Console.WriteLine("Line 2 - Value of c is {0}", c);
c = a * b;
Console.WriteLine("Line 3 - Value of c is {0}", c);
c = a / b;
Console.WriteLine("Line 4 - Value of c is {0}", c);
c = a % b;
Console.WriteLine("Line 5 - Value of c is {0}", c);
c = a++;
Console.WriteLine("Line 6 - Value of c is {0}", c);
c = a--;
Console.WriteLine("Line 7 - Value of c is {0}", c);
Console.ReadLine();
}
}
}
Output
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
Line 5 - Value of c is 1
Line 6 - Value of c is 21
Line 7 - Value of c is 22
Relational (Comparison) Operators
A Boolean result (TRUE or FALSE) is returned when two values or expressions are compared using relational operators. They play a crucial role in program conditions definition.
Less than (<): Returns TRUE in the event that the first value is less than the second. 10 < 5 is FALSE
, for instance.
Greater than (>): When the first value exceeds the second, TRUE is returned. 10 > 5 is TRUE
, for instance.
Less than or equal to (<=): If the first value is equal to or less than the second, it returns TRUE. 10 <= 5 is FALSE
, for instance.
Greater than or equal to (>=): If the first value is more than or equal to the second, it returns TRUE. 10 >= 5 is TRUE
, for instance.
Equal to (==): If the values are equal, it returns TRUE. 10 == 5 is FALSE
, for instance. In contrast to other reference types, which compare by memory location, strings exhibit unique behaviour when using ==.
Not equal to (!=): If the values are not equal, returns TRUE. For instance, 10!= 5 is TRUE
.
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
Example
using System;
namespace RelationalOperatorsExample
{
class Program
{
static void Main(string[] args)
{
int x = 10;
int y = 5;
int z = 10;
Console.WriteLine($"Is x ({x}) equal to y ({y})? : {x == y}"); // Output: False [10]
Console.WriteLine($"Is x ({x}) not equal to y ({y})? : {x != y}"); // Output: True [10]
Console.WriteLine($"Is x ({x}) greater than y ({y})? : {x > y}"); // Output: True [10]
Console.WriteLine($"Is x ({x}) less than y ({y})? : {x < y}"); // Output: False [10]
Console.WriteLine($"Is x ({x}) >= y ({y})? : {x >= y}"); // Output: True [10]
Console.WriteLine($"Is x ({x}) <= z ({z})? : {x <= z}"); // Output: True (since x is equal to z)
Console.WriteLine();
}
}
}
Output
Is x (10) equal to y (5)? : False
Is x (10) not equal to y (5)? : True
Is x (10) greater than y (5)? : True
Is x (10) less than y (5)? : False
Is x (10) >= y (5)? : True
Is x (10) <= z (10)? : True
Logical Operators
A single Boolean condition is created by combining several conditions using logical operators.
Logical AND (&&): Only when every condition is true does it return TRUE. Any condition that is FALSE turns the entire condition into FALSE. Because it is a short-circuiting operator, it ceases to evaluate as soon as the outcome is known.
- Example,
10 < 5 && 12 > 10 is FALSE
.
using System;
namespace LogicalOperatorsExample
{
class Program
{
static void Main(string[] args)
{
// Declare boolean variables. C# treats integer and Boolean data types as entirely different [8, 9].
bool isAdult = true;
bool hasLicense = false;
bool isRegistered = true;
bool isMinor = false;
Console.WriteLine("--- Initial Conditions ---");
Console.WriteLine($"Is Adult: {isAdult}");
Console.WriteLine($"Has License: {hasLicense}");
Console.WriteLine($"Is Registered: {isRegistered}");
Console.WriteLine($"Is Minor: {isMinor}");
Console.WriteLine();
// 1. Logical AND (&&) - Short-circuiting operator
// Returns 'true' only if *both* operands are 'true'.
// If the first operand evaluates to 'false', the second operand is not evaluated (short-circuit) [3, 11].
Console.WriteLine("--- Logical AND (&&) ---");
Console.WriteLine($"isAdult && hasLicense (true && false) : {isAdult && hasLicense}");
Console.WriteLine($"isAdult && isRegistered (true && true) : {isAdult && isRegistered}");
Console.WriteLine($"hasLicense && isRegistered (false && true): {hasLicense && isRegistered}");
Console.WriteLine("\n--- Logical AND (&&) Short-Circuit Example ---");
// The `CheckMethodCalled` will *not* execute if `false` evaluates first
bool andResult = CheckFalseConditionForShortCircuit() && CheckMethodCalled("This part will NOT be evaluated.");
Console.WriteLine($"Result of short-circuit AND: {andResult}");
Console.WriteLine();
}
// Helper methods to demonstrate short-circuiting behavior
static bool CheckMethodCalled(string message)
{
Console.WriteLine($"Helper Method Called: {message}");
return true;
}
static bool CheckTrueConditionForShortCircuit()
{
Console.WriteLine("First condition evaluated to TRUE.");
return true;
}
static bool CheckFalseConditionForShortCircuit()
{ https://www.onlinegdb.com/online_csharp_compiler#tab-stdin
Console.WriteLine("First condition evaluated to FALSE.");
return false;
}
}
Output
--- Initial Conditions ---
Is Adult: True
Has License: False
Is Registered: True
Is Minor: False
--- Logical AND (&&) ---
isAdult && hasLicense (true && false) : False
isAdult && isRegistered (true && true) : True
hasLicense && isRegistered (false && true): False
--- Logical AND (&&) Short-Circuit Example ---
First condition evaluated to FALSE.
Result of short-circuit AND: False
Logical OR (||): Only returns FALSE when every condition is FALSE. Any condition that is TRUE turns the entire condition into TRUE. This operator also short-circuits.
- Example: 10 < 5 || 12 > 10 is TRUE.
using System;
namespace LogicalOperatorsExample
{
class Program
{
static void Main(string[] args)
{
// Declare boolean variables. C# treats integer and Boolean data types as entirely different [8, 9].
bool isAdult = true;
bool hasLicense = false;
bool isRegistered = true;
bool isMinor = false;
Console.WriteLine("--- Initial Conditions ---");
Console.WriteLine($"Is Adult: {isAdult}");
Console.WriteLine($"Has License: {hasLicense}");
Console.WriteLine($"Is Registered: {isRegistered}");
Console.WriteLine($"Is Minor: {isMinor}");
Console.WriteLine();
// Logical OR (||) - Short-circuiting operator
// Returns 'true' if *at least one* of the operands is 'true'.
// If the first operand evaluates to 'true', the second operand is not evaluated (short-circuit).
Console.WriteLine("--- Logical OR (||) ---");
Console.WriteLine($"isAdult || hasLicense (true || false) : {isAdult || hasLicense}");
Console.WriteLine($"hasLicense || isMinor (false || false) : {hasLicense || isMinor}");
Console.WriteLine($"isRegistered || isMinor (true || false) : {isRegistered || isMinor}");
Console.WriteLine("\n--- Logical OR (||) Short-Circuit Example ---");
// The `CheckMethodCalled` will *not* execute if `true` evaluates first
bool orResult = CheckTrueConditionForShortCircuit() || CheckMethodCalled("This part will NOT be evaluated.");
Console.WriteLine($"Result of short-circuit OR: {orResult}");
Console.WriteLine();
// Note on & and |: These single ampersand/pipe operators are also logical operators in C#
// when used with boolean operands, but they are "full-circuit" (both sides are always evaluated).
// They are distinct from bitwise operators, which use the same symbols.
// Conditional logical operators (&&, ||) cannot be overloaded directly,
// but rely on their corresponding bitwise operators (&, |) which *can* be overloaded.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
// Helper methods to demonstrate short-circuiting behavior
static bool CheckMethodCalled(string message)
{
Console.WriteLine($"Helper Method Called: {message}");
return true;
}
static bool CheckTrueConditionForShortCircuit()
{
Console.WriteLine("First condition evaluated to TRUE.");
return true;
}
static bool CheckFalseConditionForShortCircuit()
{
Console.WriteLine("First condition evaluated to FALSE.");
return false;
}
}
}
Output
--- Initial Conditions ---
Is Adult: True
Has License: False
Is Registered: True
Is Minor: False
--- Logical OR (||) ---
isAdult || hasLicense (true || false) : True
hasLicense || isMinor (false || false) : False
isRegistered || isMinor (true || false) : True
--- Logical OR (||) Short-Circuit Example ---
First condition evaluated to TRUE.
Result of short-circuit OR: True
Logical NOT (!): Flips its operand’s logical state around. The argument is preceded by this unary operator.
- Example:
!(10 < 5 && 12 > 10) is TRUE
.
using System;
namespace LogicalOperatorsExample
{
class Program
{
static void Main(string[] args)
{
// Declare boolean variables. C# treats integer and Boolean data types as entirely different.
bool isAdult = true;
bool hasLicense = false;
bool isRegistered = true;
bool isMinor = false;
Console.WriteLine("--- Initial Conditions ---");
Console.WriteLine($"Is Adult: {isAdult}");
Console.WriteLine($"Has License: {hasLicense}");
Console.WriteLine($"Is Registered: {isRegistered}");
Console.WriteLine($"Is Minor: {isMinor}");
Console.WriteLine();
// 3. Logical NOT (!) - Unary operator
// Reverses the Boolean value of its operand.
Console.WriteLine("--- Logical NOT (!) ---");
Console.WriteLine($"!isAdult (true) : {!isAdult}");
Console.WriteLine($"!hasLicense (false) : {!hasLicense}");
Console.WriteLine($"!(10 > 5) (true expression) : {!(10 > 5)}");
Console.WriteLine($"!(7 == 5) (false expression): {!(7 == 5)}");
Console.WriteLine();
// Note on & and |: These single ampersand/pipe operators are also logical operators in C#
// when used with boolean operands, but they are "full-circuit" (both sides are always evaluated).
// They are distinct from bitwise operators, which use the same symbols.
// Conditional logical operators (&&, ||) cannot be overloaded directly,
// but rely on their corresponding bitwise operators (&, |) which *can* be overloaded.
}
// Helper methods to demonstrate short-circuiting behavior
static bool CheckMethodCalled(string message)
{
Console.WriteLine($"Helper Method Called: {message}");
return true;
}
static bool CheckTrueConditionForShortCircuit()
{
Console.WriteLine("First condition evaluated to TRUE.");
return true;
}
static bool CheckFalseConditionForShortCircuit()
{
Console.WriteLine("First condition evaluated to FALSE.");
return false;
}
}
}
Output
--- Initial Conditions ---
Is Adult: True
Has License: False
Is Registered: True
Is Minor: False
--- Logical NOT (!) ---
!isAdult (true) : False
!hasLicense (false) : True
!(10 > 5) (true expression) : False
!(7 == 5) (false expression): True
Exclusive OR (^): If both operands are TRUE, then TRUE is returned. It returns FALSE if the value of both operands is the same. A full-circuit operator is what this is.
- For instance:
true ^ true
yields false, whereastrue ^ false
returns true.
The distinction between bitwise operators (&, |, ~) and logical operators (&&, ||,!) must be made. The “full-circuit” logical operators, the single vertical bar | and the single ampersand &, evaluate both operands even if the first operand already determines the outcome.
Operator | Description | Example |
---|---|---|
&& | Logical AND (returns true if both operands are true) | a && b |
|| | Logical OR (returns true if at least one operand is true) | a || b |
! | Logical NOT (inverts the boolean value) | !a |
Increment & Decrement Operators
To alter an operand’s value by one, utilise these unary operators.
Increment (++): The operand’s current value is increased by one using the increment (++) function.
Decrement (–): One is deducted from the operand’s current value using the increment (–) function.
They are useful in two ways:
Prefix (++a or –a): The operation is carried out prior to the value being utilised in an expression by using the prefix (++a or –a).
Example: int x = 42; Console.WriteLine(++x); // Output: 43
.
using System;
namespace IncrementDecrementOperators
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--- Demonstrating Increment and Decrement Operators ---");
Console.WriteLine();
// Post-Increment (variable++)
// The value of 'numA' is used first, then incremented.
int numA = 5;
Console.WriteLine($"Initial numA: {numA}");
int postIncrementResult = numA++;
Console.WriteLine($"numA++ (used original value 5, then incremented): {postIncrementResult}");
Console.WriteLine($"numA after post-increment: {numA}");
Console.WriteLine();
// Pre-Increment (++variable)
// The value of 'numB' is incremented first, then the new value is used.
int numB = 10;
Console.WriteLine($"Initial numB: {numB}");
int preIncrementResult = ++numB;
Console.WriteLine($"++numB (incremented to 11, then used): {preIncrementResult}");
Console.WriteLine($"numB after pre-increment: {numB}");
Console.WriteLine();
}
}
}
Output
--- Demonstrating Increment and Decrement Operators ---
Initial numA: 5
numA++ (used original value 5, then incremented): 5
numA after post-increment: 6
Initial numB: 10
++numB (incremented to 11, then used): 11
numB after pre-increment: 11
Postfix (a++ or a–): Prior to performing the increment/decrement operation, the expression uses the operand’s initial value.
Example: int x = 42; Console.WriteLine(x++); // Output: 42 (x becomes 43 after this line)
using System;
namespace IncrementDecrementOperators
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--- Demonstrating Increment and Decrement Operators ---");
Console.WriteLine();
// Post-Decrement (variable--)
// The value of 'numC' is used first, then decremented.
int numC = 15;
Console.WriteLine($"Initial numC: {numC}");
int postDecrementResult = numC--;
Console.WriteLine($"numC-- (used original value 15, then decremented): {postDecrementResult}");
Console.WriteLine($"numC after post-decrement: {numC}");
Console.WriteLine();
// Pre-Decrement (--variable)
// The value of 'numD' is decremented first, then the new value is used.
int numD = 20;
Console.WriteLine($"Initial numD: {numD}");
int preDecrementResult = --numD;
Console.WriteLine($"--numD (decremented to 19, then used): {preDecrementResult}");
Console.WriteLine($"numD after pre-decrement: {numD}");
Console.WriteLine();
}
}
}
Output
--- Demonstrating Increment and Decrement Operators ---
Initial numC: 15
numC-- (used original value 15, then decremented): 15
numC after post-decrement: 14
Initial numD: 20
--numD (decremented to 19, then used): 19
numD after pre-decrement: 19
Operator | Description | Example |
---|---|---|
++ | Increment (pre-increment: ++a , post-increment: a++ ) | ++a , a++ |
-- | Decrement (pre-decrement: --a , post-decrement: a-- ) | --a , a-- |
Assignment Operators
To provide a left-hand side variable (Lvalue) a right-hand side value (Rvalue), assignment operators are utilised. = is the most basic assignment operator.
Simple Assignment (=): Transfers the right operand’s value to the left operand. For instance: A = 15.
Compound Assignment Operators: Add a bitwise or arithmetic action to an assignment. They provide an abbreviated notation. The expression operand1 = operand1 operator operand2 is equal to operand1 operator= operand2.
- Add and Assign (+=): A += 10 is A = A + 10.
- Subtract and Assign (-=): A -= B is A = A – B.
- Multiply and Assign (*=): A *= B is A = A * B.
- Divide and Assign (/=): A /= B is A = A / B.
- Modulus and Assign (%=): A %= B is A = A % B.
Example
using System;
namespace AssignmentOperatorsExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--- Demonstrating Assignment Operators ---");
Console.WriteLine();
// 1. Simple Assignment Operator (=)
// Assigns the value of the right-hand operand to the left-hand operand.
int a = 10; // Assigns 10 to 'a'
Console.WriteLine($"Initial value of a: {a}");
string message = "Hello C#"; // Assigns a string literal to 'message'
Console.WriteLine($"Initial message: {message}");
Console.WriteLine();
// Cascade Assignment: Multiple variables can be assigned the same value from right to left.
int x, y, z;
x = y = z = 25; // x, y, and z all become 25
Console.WriteLine($"Cascade assignment: x={x}, y={y}, z={z}");
Console.WriteLine();
// 2. Compound Assignment Operators
// These combine an operation (like addition, subtraction, etc.) with assignment.
// Syntax: operand1 operator= operand2; is equivalent to operand1 = operand1 operator operand2;
int num = 50;
Console.WriteLine($"Starting value for compound operations (num): {num}");
Console.WriteLine();
// Addition Assignment (+=)
// num = num + 10;
num += 10;
Console.WriteLine($"num += 10; -> num is now: {num}");
// Subtraction Assignment (-=)
// num = num - 5;
num -= 5;
Console.WriteLine($"num -= 5; -> num is now: {num}");
// Multiplication Assignment (*=)
// num = num * 2; [4, 5, 9]
num *= 2;
Console.WriteLine($"num *= 2; -> num is now: {num}");
// Division Assignment (/=)
// num = num / 10;
num /= 10;
Console.WriteLine($"num /= 10; -> num is now: {num}");
// Modulo Assignment (%=)
// num = num % 3;
num %= 3;
Console.WriteLine($"num %= 3; -> num is now: {num}");
Console.WriteLine();
// Note: Confusion between assignment (=) and equality (==) operators is a common error.
// In C#, expressions in if and while statements must resolve to a bool value.
// The compiler will catch accidental use of '=' instead of '==' in Boolean contexts.
}
}
}
Output
--- Demonstrating Assignment Operators ---
Initial value of a: 10
Initial message: Hello C#
Cascade assignment: x=25, y=25, z=25
Starting value for compound operations (num): 50
num += 10; -> num is now: 60
num -= 5; -> num is now: 55
num *= 2; -> num is now: 110
num /= 10; -> num is now: 11
num %= 3; -> num is now: 2
Bitwise Operators
Operations on the binary representation (bits) of numerical data are carried out using bitwise operators.
Bitwise AND (&): Comparing similar bits yields a value of 1 if both bits are 1, and 0 otherwise.
- Example: int a = 60; // 0011 1100, int b = 13; // 0000 1101 int c = a & b; // 12 = 0000 1100.
Bitwise OR (|): compares matching bits; if at least one of them is 1, the result is 1; if not, it is 0.
- Example: int c = a | b; // 61 = 0011 1101.
Bitwise XOR (^): compares matching bits; if they vary, the result is 1, else it is 0.
- Example: int c = a ^ b; // 49 = 0011 0001.
Bitwise Complement (~): All bits are inverted (0 becomes 1, 1 becomes 0).
- Example: int a = 60; // 0011 1100, int c = ~a; // -61.
Left Shift (<<): moves every bit by a predetermined amount to the left. On the right, new zeros are added, and bits that have been moved to the left are deleted.
- Example: int a = 60; // 0011 1100, int c = a << 2; // 240 = 1111 0000.
Right Shift (>>): moves every bit by a predetermined amount to the right. Bits that are moved to the right are thrown out.
- Example: int a = 60; // 0011 1100, int c = a >> 2; // 15 = 0000 1111.
Operator | Description | Example |
---|---|---|
& | Bitwise AND | a & b |
| | Bitwise OR | a | b |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT (one’s complement) | ~a |
<< | Left Shift | a << b |
>> | Right Shift | a >> b |
Example
using System;
namespace BitwiseOperatorsExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--- Demonstrating Bitwise Operators ---");
Console.WriteLine();
// Initial values for demonstration
int a = 60; // Binary: 0011 1100
int b = 13; // Binary: 0000 1101
int c;
Console.WriteLine($"Initial a: {a} (Binary: {Convert.ToString(a, 2).PadLeft(8, '0')})");
Console.WriteLine($"Initial b: {b} (Binary: {Convert.ToString(b, 2).PadLeft(8, '0')})");
Console.WriteLine();
// 1. Bitwise AND (&)
// Compares each bit; result bit is 1 only if both corresponding bits are 1.
// 0011 1100 (a)
// & 0000 1101 (b)
// = 0000 1100 (12)
c = a & b;
Console.WriteLine($"a & b: {c} (Binary: {Convert.ToString(c, 2).PadLeft(8, '0')}) [15, 41, 42]");
Console.WriteLine();
// 2. Bitwise OR (|)
// Compares each bit; result bit is 1 if at least one corresponding bit is 1.
// 0011 1100 (a)
// | 0000 1101 (b)
// = 0011 1101 (61)
c = a | b;
Console.WriteLine($"a | b: {c} (Binary: {Convert.ToString(c, 2).PadLeft(8, '0')}) [15, 41, 42]");
Console.WriteLine();
// 3. Bitwise XOR (^)
// Compares each bit; result bit is 1 if corresponding bits are different.
// 0011 1100 (a)
// ^ 0000 1101 (b)
// = 0011 0001 (49)
c = a ^ b;
Console.WriteLine($"a ^ b: {c} (Binary: {Convert.ToString(c, 2).PadLeft(8, '0')}) [15, 41, 42]");
Console.WriteLine();
// 4. Bitwise NOT (~)
// Inverts all bits of the operand.
// For 'int a = 60': 00000000 00000000 00000000 00111100
// ~ results in: 11111111 11111111 11111111 11000011 (which is -61 in two's complement for int)
c = ~a;
Console.WriteLine($"~a: {c} (Binary: {Convert.ToString(c, 2)}) [43]");
Console.WriteLine();
// 5. Left Shift (<<)
// Shifts bits to the left, fills with 0s on the right.
// a << 2: 0011 1100 << 2 = 1111 0000 (240)
c = a << 2;
Console.WriteLine($"a << 2: {c} (Binary: {Convert.ToString(c, 2).PadLeft(8, '0')}) [15, 43]");
Console.WriteLine();
// 6. Right Shift (>>)
// Shifts bits to the right, fills with 0s on the left for positive signed integers.
// a >> 2: 0011 1100 >> 2 = 0000 1111 (15)
c = a >> 2;
Console.WriteLine($"a >> 2: {c} (Binary: {Convert.ToString(c, 2).PadLeft(8, '0')}) [15, 43]");
Console.WriteLine();
}
}
}
Output
[?2004l
--- Demonstrating Bitwise Operators ---
Initial a: 60 (Binary: 00111100)
Initial b: 13 (Binary: 00001101)
a & b: 12 (Binary: 00001100) [15, 41, 42]
a | b: 61 (Binary: 00111101) [15, 41, 42]
a ^ b: 49 (Binary: 00110001) [15, 41, 42]
~a: -61 (Binary: 11111111111111111111111111000011) [43]
a << 2: 240 (Binary: 11110000) [15, 43]
a >> 2: 15 (Binary: 00001111) [15, 43]
Conditional Operator ()
The sole ternary operator in C# that is utilised for decision-making is this one. It assesses a Boolean condition and, depending on the outcome, does one of two actions.
- Syntax:
Condition ? TRUE_Part : FALSE_Part;
. - Execution and return of TRUE_Part occur when Condition is TRUE; otherwise, FALSE_Part occurs.
- Example: int A = (10 < 15) ? 100 : 200; // A will be 100.
- Example: int a = 10; int b = (a == 1) ? 20 : 30; Console.WriteLine(b); // Output: 30.
using System;
using System.Collections.Generic;
namespace ConditionalOperatorExample
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("--- Basic Conditional Operator ---");
int a = 10;
int b = 5;
// Example 1: Simple comparison
// If a > b is true, resultString will be "a is greater", otherwise "b is greater or equal"
string resultString = (a > b) ? "a is greater" : "b is greater or equal";
Console.WriteLine($"Result 1: {resultString}"); // Output: a is greater [20]
int c = 10;
int d = 10;
// Example: int num = a == b ? 1 : -1;
int numResult = (c == d) ? 1 : -1;
Console.WriteLine($"Result 2 (num): {numResult}"); // Output: 1 [20]
}
}
}
Output
--- Basic Conditional Operator ---
Result 1: a is greater
Result 2 (num): 1
Special Operators
Several additional crucial operators are included in C#:
Member Access (.): used to retrieve a class or object’s fields, methods, or properties.
- Example: Console.WriteLine(DateTime.Now);.
Indexer ([]): Used to retrieve array elements using an index or string characters. utilised for collection indexing as well.
- Example: int[] arr = { 1, 2, 3 }; Console.WriteLine(arr); // Output: 1.
Parentheses (()): Used to specifically regulate the expression and operation evaluation order.
Type Conversion (Cast Operator (type)): A value can be manually converted between different data types using this method.
- Example: double half = (double)1 / 2; Console.WriteLine(half); // Output: 0.5.
as
operator: Utilized for the conversion of types. It returns null rather than raising an exception if the conversion is invalid.
is
operator: Determines whether an object is compatible with a certain type.
- Example: string s = “Beer”; Console.WriteLine(s is string); // Output: True.
new
operator: Utilized for the creation and initialisation of new objects or type instances.
sizeof
operator: Gives back the size of a compile-time known value type in bytes. It doesn’t function with instances or variables.
- Example: Console.WriteLine(“The size of int is {0}”, sizeof(int));.
typeof
operator: It Is used to retrieve the System.Type object for a given type.
- Example: System.Type type = typeof(Point);.
Null-Coalescing Operator (??): Returns the operand on the left if it is not null, and the operand on the right if it is.
- Example: string name =
null; Console.WriteLine(name ?? "(no name)"); // Output: (no name)
. - Example:
int? e = null; int? f = null; int g = e ?? f ?? -1; // g will be -1
.
Null-Conditional Operator (?. or ?[]): Only if the operand is not null does it access a member or element; otherwise, the operation short-circuits and returns null, preventing NullReferenceExceptions.
- Example:
var zipcode = myEmployee?.Address?.ZipCode;
. - Example:
char? letter = letters?;
.
nameof
operator: Compile-time evaluation of a variable, type, or member that returns the unqualified name as a string.
- Example:
int counter = 10; nameof(counter); // Returns "counter"
.
Lambda Operator (=>): LINQ queries frequently use this to define delegates and declare lambda expressions.
Operator Precedence and Associativity
Operators in an expression are evaluated in order of precedence and associativity, with higher precedence operators being evaluated before lower precedence operators.
- The default priority can be expressly overridden by using
brackets ()
. - When evaluated from left to right, the majority of C#’s binary operators are left-associative.
- Right-associative (evaluated from right to left) are the conditional operators (?:,??) and assignment operators (=, +=, etc.).
- Associative operators are not unary operators.
For instance, in x + y / 100
, y / 100
is calculated first because division (/) has a greater precedence than addition (+
). To fix this, you would use brackets: (x + y) / 100
.
Operator Overloading
An overloaded operator is essentially a specialised method call that aids in abstracting operations, and C# allows user-defined types (classes or structs) to overload many operators, allowing them to work with instances of those types in a natural way by defining public static member functions using the operator keyword.
Overloadable Operators
- Unary operators: +, -, !, ~, ++, –, true, false.
- Example (unary minus):
- Binary operators: +, -, *, /, %, &, |, ^, <<, >>.
- Example (addition for ComplexNumber):
- Comparison operators: ==, !=, <, >, <=, >=. These must be overloaded in pairs (e.g., if == is overloaded, != must also be).
Non-Overloadable Operators
- but they are assessed using
&
and|
, which can be overloaded, conditional logical operators(&&, ||)
. - Array indexing operator (
[]
) (instead of indexers, which can be defined). - Using both explicit and implicit keywords, new conversion operators can be written using the cast operator (()).
- The assignment operators
(=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=)
depend on the underlying binary operators, which are susceptible to overload. - Other operators include
sizeof, ., typeof, new, is,?:, ->
.
You can aslo read What Is C# Variables And How To Initialize & Assign Values