C# Operators


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.

OperatorDescriptionExample
+Additiona + b
-Subtractiona - b
*Multiplicationa * b
/Divisiona / b
%Modulus (remainder)a % b

Example:

csharp
1int 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.

OperatorDescriptionExample
==Equal toa == b
!=Not equal toa != b
>Greater thana > b
<Less thana < b
>=Greater than or equal toa >= b
<=Less than or equal toa <= b

Example:

csharp
1int 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.

OperatorDescriptionExample
&&Logical ANDa && b
``
!Logical NOT!a

Example:

csharp
1bool 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.

OperatorDescriptionExample
&Bitwise ANDa & b
``Bitwise OR
^Bitwise XORa ^ b
~Bitwise NOT~a
<<Left shifta << 1
>>Right shifta >> 1

Example:

csharp
1using 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

Assignment operators are used to assign values to variables. The most common assignment operator is the equals sign =. However, C# also provides several compound assignment operators that combine assignment with another operation.

Detailed Examples

Here are detailed examples for each operator:

  1. Simple Assignment (=)

    csharp
    1int a = 10; // Assigns 10 to a 2Console.WriteLine(a); // Output: 10
  2. Addition Assignment (+=)

    csharp
    1a += 5; // Now a = a + 5 2Console.WriteLine(a); // Output: 15
  3. Subtraction Assignment (-=)

    csharp
    1a -= 3; // Now a = a - 3 2Console.WriteLine(a); // Output: 12
  4. Multiplication Assignment (*=)

    csharp
    1a *= 2; // Now a = a * 2 2Console.WriteLine(a); // Output: 24
  5. Division Assignment (/=)

    csharp
    1a /= 4; // Now a = a / 4 2Console.WriteLine(a); // Output: 6
  6. Modulus Assignment (%=)

    csharp
    1a %= 4; // Now a = a % 4 2Console.WriteLine(a); // Output: 2
  7. Bitwise AND Assignment (&=)

    csharp
    1a &= 3; // Now a = a & 3 2Console.WriteLine(a); // Output: 2 (Binary: 0010)
  8. Bitwise OR Assignment (|=)

    csharp
    1a |= 3; // Now a = a | 3 2Console.WriteLine(a); // Output: 3 (Binary: 0011)
  9. Bitwise XOR Assignment (^=)

    csharp
    1a ^=

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:

csharp
1condition ? value_if_true : value_if_false

Example:

csharp
1int 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:

csharp
1nullableValue ?? defaultValue

Example:

csharp
1string 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:

csharp
1nullableValue ??= defaultValue

Example:

csharp
1string 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:

csharp
1object is Type

Example:

csharp
1object 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:

csharp
1if (obj is Type variableName) 2{ 3 // variableName can be used as an instance of Type 4}

Example:

csharp
1object 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:

csharp
1object as Type

Example:

csharp
1object 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:

csharp
1sizeof(Type)

Example:

csharp
1int 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:

csharp
1unsafe 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 LevelOperator(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

  1. Parentheses (()):

    • Parentheses have the highest precedence. Expressions inside parentheses are evaluated first.
    • Example: result = (a + b) * c; evaluates a + b first.
  2. Unary Operators (++--+-!~):

    • Unary operators have the next highest precedence and are evaluated before binary operators.
    • Example: result = -a + b; evaluates -a before adding b.
  3. Multiplication, Division, and Modulus (*/%):

    • These operators are evaluated next, from left to right.
    • Example: result = a * b / c; evaluates a * b first, then divides by c.
  4. Addition and Subtraction (+-):

    • Evaluated after multiplication, division, and modulus, from left to right.
    • Example: result = a + b - c; evaluates a + b first, then subtracts c.
  5. Bitwise Shift Operators (<<>>):

    • These operators shift bits left or right and are evaluated next.
    • Example: result = a << 2; shifts a's bits to the left by 2 positions.
  6. Relational Operators (<<=>>=):

    • Evaluated after arithmetic operations.
    • Example: result = a < b; evaluates to true or false.
  7. Equality Operators (==!=):

    • Evaluated after relational operators.
    • Example: result = (a == b); checks if a is equal to b.
  8. Bitwise AND (&):

    • Evaluated after equality operators.
    • Example: result = a & b; performs a bitwise AND operation.
  9. Bitwise XOR (^):

    • Evaluated after bitwise AND.
    • Example: result = a ^ b; performs a bitwise XOR operation.
  10. Bitwise OR (|):

    • Evaluated after bitwise XOR.
    • Example: result = a | b; performs a bitwise OR operation.
  11. Logical AND (&&):

    • Evaluated after bitwise operators.
    • Example: result = (a > 0 && b < 10); checks both conditions.
  12. Logical OR (||):

    • Evaluated after logical AND.

Talk to us?

Post your blog