Operators are special symbols that perform operations on variables and values. C# provides a rich set of operators that can be categorized into several groups based on their functionality. Below is a detailed overview of the various types of operators in C#, along with examples for each type.
1. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
Example:
csharp1int a = 10; 2int b = 3; 3 4Console.WriteLine("Addition: " + (a + b)); // 13 5Console.WriteLine("Subtraction: " + (a - b)); // 7 6Console.WriteLine("Multiplication: " + (a * b)); // 30 7Console.WriteLine("Division: " + (a / b)); // 3 8Console.WriteLine("Modulus: " + (a % b)); // 1
2. Relational Operators
Relational operators are used to compare two values.
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:
csharp1int a = 10; 2int b = 20; 3 4Console.WriteLine("Equal: " + (a == b)); // False 5Console.WriteLine("Not Equal: " + (a != b)); // True 6Console.WriteLine("Greater Than: " + (a > b)); // False 7Console.WriteLine("Less Than: " + (a < b)); // True 8Console.WriteLine("Greater Than or Equal: " + (a >= b)); // False 9Console.WriteLine("Less Than or Equal: " + (a <= b)); // True
3. Logical Operators
Logical operators are used to perform logical operations, often with boolean values.
Operator | Description | Example |
---|---|---|
&& | Logical AND | a && b |
` | ` | |
! | Logical NOT | !a |
Example:
csharp1bool a = true; 2bool b = false; 3 4Console.WriteLine("Logical AND: " + (a && b)); // False 5Console.WriteLine("Logical OR: " + (a || b)); // True 6Console.WriteLine("Logical NOT: " + (!a)); // False
4. Bitwise Operators
Bitwise operators perform operations on bits and are used with integer types.
Operator | Description | Example |
---|---|---|
& | Bitwise AND | a & b |
` | ` | Bitwise OR |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT | ~a |
<< | Left shift | a << 1 |
>> | Right shift | a >> 1 |
Example:
csharp1using System; 2 3class Program 4{ 5 static void Main() 6 { 7 int a = 12; // In binary: 0000 1100 8 int b = 5; // In binary: 0000 0101 9 10 // Bitwise AND 11 int andResult = a & b; // 0000 0100 (4 in decimal) 12 Console.WriteLine($"Bitwise AND: {a} & {b} = {andResult} (binary: {Convert.ToString(andResult, 2).PadLeft(8, '0')})"); 13 14 // Bitwise OR 15 int orResult = a | b; // 0000 1101 (13 in decimal) 16 Console.WriteLine($"Bitwise OR: {a} | {b} = {orResult} (binary: {Convert.ToString(orResult, 2).PadLeft(8, '0')})"); 17 18 // Bitwise XOR 19 int xorResult = a ^ b; // 0000 1001 (9 in decimal) 20 Console.WriteLine($"Bitwise XOR: {a} ^ {b} = {xorResult} (binary: {Convert.ToString(xorResult, 2).PadLeft(8, '0')})"); 21 22 // Bitwise NOT 23 int notResult = ~a; // Inverts the bits of a (for 12: 1111 0011, which is -13 in decimal due to two's complement) 24 Console.WriteLine($"Bitwise NOT: ~{a} = {notResult} (binary: {Convert.ToString(notResult, 2).PadLeft(8, '0')})"); 25 26 // Left Shift 27 int leftShiftResult = a << 1; // 0001 1000 (24 in decimal) 28 Console.WriteLine($"Left Shift: {a} << 1 = {leftShiftResult} (binary: {Convert.ToString(leftShiftResult, 2).PadLeft(8, '0')})"); 29 30 // Right Shift 31 int rightShiftResult = a >> 1; // 0000 0110 (6 in decimal) 32 Console.WriteLine($"Right Shift: {a} >> 1 = {rightShiftResult} (binary: {Convert.ToString(rightShiftResult, 2).PadLeft(8, '0')})"); 33 } 34}
4. Assignment Operators
=
. However, C# also provides several compound assignment operators that combine assignment with another operation.Detailed Examples
Here are detailed examples for each operator:
Simple Assignment (
=
)csharp1int a = 10; // Assigns 10 to a 2Console.WriteLine(a); // Output: 10
Addition Assignment (
+=
)csharp1a += 5; // Now a = a + 5 2Console.WriteLine(a); // Output: 15
Subtraction Assignment (
-=
)csharp1a -= 3; // Now a = a - 3 2Console.WriteLine(a); // Output: 12
Multiplication Assignment (
*=
)csharp1a *= 2; // Now a = a * 2 2Console.WriteLine(a); // Output: 24
Division Assignment (
/=
)csharp1a /= 4; // Now a = a / 4 2Console.WriteLine(a); // Output: 6
Modulus Assignment (
%=
)csharp1a %= 4; // Now a = a % 4 2Console.WriteLine(a); // Output: 2
Bitwise AND Assignment (
&=
)csharp1a &= 3; // Now a = a & 3 2Console.WriteLine(a); // Output: 2 (Binary: 0010)
Bitwise OR Assignment (
|=
)csharp1a |= 3; // Now a = a | 3 2Console.WriteLine(a); // Output: 3 (Binary: 0011)
Bitwise XOR Assignment (
^=
)csharp1a ^=
4. Miscellaneous Operators
1. Conditional (Ternary) Operator (?:
)
The conditional operator is a shorthand for the if-else
statement. It takes three operands and evaluates a boolean expression to return one of two values.
Syntax:
csharp1condition ? value_if_true : value_if_false
Example:
csharp1int a = 10; 2int b = 20; 3int max = (a > b) ? a : b; // max will be assigned the value of b (20) 4Console.WriteLine(max); // Output: 20
2. Null Coalescing Operator (??
)
The null coalescing operator is used to provide a default value when dealing with nullable types. It returns the left-hand operand if it is not null; otherwise, it returns the right-hand operand.
Syntax:
csharp1nullableValue ?? defaultValue
Example:
csharp1string name = null; 2string displayName = name ?? "Default Name"; // displayName will be "Default Name" 3Console.WriteLine(displayName); // Output: Default Name
3. Null Coalescing Assignment Operator (??=
)
The null coalescing assignment operator assigns the right-hand operand to the left-hand operand only if the left-hand operand is null.
Syntax:
csharp1nullableValue ??= defaultValue
Example:
csharp1string name = null; 2name ??= "Default Name"; // name will be assigned "Default Name" 3Console.WriteLine(name); // Output: Default Name
4. Type Testing Operator (is
)
The is
operator is used to check if an object is of a specific type. It returns true
if the object is of the specified type; otherwise, it returns false
.
Syntax:
csharp1object is Type
Example:
csharp1object obj = "Hello"; 2bool isString = obj is string; // isString will be true 3Console.WriteLine(isString); // Output: True
5. Type Pattern Matching (C# 7.0 and later)
Type pattern matching allows you to test an object's type and cast it in a single operation.
Syntax:
csharp1if (obj is Type variableName) 2{ 3 // variableName can be used as an instance of Type 4}
Example:
csharp1object obj = "Hello"; 2if (obj is string str) 3{ 4 Console.WriteLine(str.Length); // Output: 5 5}
6. As Operator
The as
operator is used for safe type casting. It attempts to cast an object to a specified type and returns null
if the cast fails instead of throwing an exception.
Syntax:
csharp1object as Type
Example:
csharp1object obj = "Hello"; 2string str = obj as string; // str will be "Hello" 3Console.WriteLine(str); // Output: Hello 4 5object num = 123; 6string strNum = num as string; // strNum will be null 7Console.WriteLine(strNum == null); // Output: True
7. Size-of Operator (sizeof
)
The sizeof
operator is used to obtain the size (in bytes) of a type. It works only with unmanaged types.
Syntax:
csharp1sizeof(Type)
Example:
csharp1int sizeOfInt = sizeof(int); // sizeOfInt will be 4 2Console.WriteLine(sizeOfInt); // Output: 4
8. Pointer Type Operators (*
, &
)
These operators are used in unsafe code contexts to work with pointers.
*
is used to declare pointer types or to dereference pointers.&
is used to get the address of a variable.
Example:
csharp1unsafe 2{ 3 int number = 10; 4 int* p = &number; // p now holds the address of number 5 Console.WriteLine(*p); // Output: 10 (dereferencing p) 6}
Operator Precedence Table
Below is a table that lists the operators in C# along with their precedence levels (from highest to lowest). Operators with the same precedence level are evaluated from left to right, except for certain operators that are evaluated from right to left.
Precedence Level | Operator(s) | Description |
---|---|---|
1 | () | Parentheses (used for grouping) |
2 | ++ , -- , + , - , ! , ~ | Unary operators (increment, decrement, unary plus, unary minus, logical NOT, bitwise NOT) |
3 | * , / , % | Multiplication, division, and modulus |
4 | + , - | Addition and subtraction |
5 | << , >> | Bitwise shift left and right |
6 | < , <= , > , >= | Relational operators |
7 | == , != | Equality and inequality operators |
8 | & | Bitwise AND |
9 | ^ | Bitwise XOR |
10 | ` | ` |
11 | && | Logical AND |
12 | ` | |
13 | ? : | Conditional (ternary) operator |
14 | = | Assignment operator |
15 | += , -= , *= , /= , %= , &= , ` | =, ^=, <<=, >>=` |
16 | , | Comma operator |
Detailed Explanation of Precedence Levels
Parentheses (
()
):- Parentheses have the highest precedence. Expressions inside parentheses are evaluated first.
- Example:
result = (a + b) * c;
evaluatesa + b
first.
Unary Operators (
++
,--
,+
,-
,!
,~
):- Unary operators have the next highest precedence and are evaluated before binary operators.
- Example:
result = -a + b;
evaluates-a
before addingb
.
Multiplication, Division, and Modulus (
*
,/
,%
):- These operators are evaluated next, from left to right.
- Example:
result = a * b / c;
evaluatesa * b
first, then divides byc
.
Addition and Subtraction (
+
,-
):- Evaluated after multiplication, division, and modulus, from left to right.
- Example:
result = a + b - c;
evaluatesa + b
first, then subtractsc
.
Bitwise Shift Operators (
<<
,>>
):- These operators shift bits left or right and are evaluated next.
- Example:
result = a << 2;
shiftsa
's bits to the left by 2 positions.
Relational Operators (
<
,<=
,>
,>=
):- Evaluated after arithmetic operations.
- Example:
result = a < b;
evaluates totrue
orfalse
.
Equality Operators (
==
,!=
):- Evaluated after relational operators.
- Example:
result = (a == b);
checks ifa
is equal tob
.
Bitwise AND (
&
):- Evaluated after equality operators.
- Example:
result = a & b;
performs a bitwise AND operation.
Bitwise XOR (
^
):- Evaluated after bitwise AND.
- Example:
result = a ^ b;
performs a bitwise XOR operation.
Bitwise OR (
|
):- Evaluated after bitwise XOR.
- Example:
result = a | b;
performs a bitwise OR operation.
Logical AND (
&&
):- Evaluated after bitwise operators.
- Example:
result = (a > 0 && b < 10);
checks both conditions.
Logical OR (
||
):- Evaluated after logical AND.