C# Operators

In C#, operators are special symbols that perform operations on variables and values. They are categorized based on their functionality. This comprehensive overview covers various types of operators in C#:

1. Arithmetic Operators

These operators perform basic mathematical operations.

- Addition (`+`): Adds two operands.
- Subtraction (`-`): Subtracts the second operand from the first.
- Multiplication (`*`): Multiplies two operands.
- Division (`/`): Divides the numerator by the denominator.
- Modulus (`%`): Returns the remainder of division.

Example:
using System;

class Program
{
    static void Main()
    {
        int a = 10;
        int b = 3;
        Console.WriteLine("Addition: " + (a + b)); // Output: 13
        Console.WriteLine("Subtraction: " + (a - b)); // Output: 7
        Console.WriteLine("Multiplication: " + (a * b)); // Output: 30
        Console.WriteLine("Division: " + (a / b)); // Output: 3
        Console.WriteLine("Modulus: " + (a % b)); // Output: 1
    }
}

Output:
Addition: 13
Subtraction: 7
Multiplication: 30
Division: 3
Modulus: 1

2. Relational Operators

These operators compare two values and return a boolean result.

- Equal to (`==`): Checks if two operands are equal.
- Not equal to (`!=`): Checks if two operands are not equal.
- Greater than (`>`): Checks if the left operand is greater than the right.
- Less than (`<`): Checks if the left operand is less than the right.
- Greater than or equal to (`>=`): Checks if the left operand is greater than or equal to the right.
- Less than or equal to (`<=`): Checks if the left operand is less than or equal to the right.

Example:
using System;

class Program
{
    static void Main()
    {
        int x = 5;
        int y = 10;
        Console.WriteLine("x == y: " + (x == y)); // Output: False
        Console.WriteLine("x != y: " + (x != y)); // Output: True
        Console.WriteLine("x > y: " + (x > y)); // Output: False
        Console.WriteLine("x < y: " + (x < y)); // Output: True
        Console.WriteLine("x >= y: " + (x >= y)); // Output: False
        Console.WriteLine("x <= y: " + (x <= y)); // Output: True
    }
}

Output:
x == y: False
x != y: True
x > y: False
x < y: True
x >= y: False
x <= y: True

3. Logical Operators

These operators perform logical operations and return a boolean result.

- Logical AND (`&&`): Returns true if both operands are true.
- Logical OR (`||`): Returns true if at least one operand is true.
- Logical NOT (`!`): Reverses the logical state of its operand.

Example:
using System;

class Program
{
    static void Main()
    {
        bool a = true;
        bool b = false;
        Console.WriteLine("a && b: " + (a && b)); // Output: False
        Console.WriteLine("a || b: " + (a || b)); // Output: True
        Console.WriteLine("!a: " + (!a)); // Output: False
    }
}

Output:
a && b: False
a || b: True
!a: False

4. Bitwise Operators

These operators perform operations on the binary representations of numbers.

- Bitwise AND (`&`): Compares each bit; returns 1 if both bits are 1.
- Bitwise OR (`|`): Compares each bit; returns 1 if at least one bit is 1.
- Bitwise XOR (`^`): Compares each bit; returns 1 if bits are different.
- Bitwise NOT (`~`): Inverts the bits.
- Left Shift (`<<`): Shifts bits to the left, filling with zeros.
- Right Shift (`>>`): Shifts bits to the right.

Example:
using System;

class Program
{
    static void Main()
    {
        int a = 5; // 0101 in binary
        int b = 3; // 0011 in binary
        Console.WriteLine("a & b: " + (a & b)); // Output: 1 (0001)
        Console.WriteLine("a | b: " + (a | b)); // Output: 7 (0111)
        Console.WriteLine("a ^ b: " + (a ^ b)); // Output: 6 (0110)
        Console.WriteLine("~a: " + (~a)); // Output: -6 (inverts bits)
        Console.WriteLine("a << 1: " + (a << 1)); // Output: 10 (1010)
        Console.WriteLine("a >> 1: " + (a >> 1)); // Output: 2 (0010)
    }
}

Output:
a & b: 1
a | b: 7
a ^ b: 6
~a: -6
a << 1: 10
a >> 1: 2

5. Assignment Operators

These operators assign values to variables.

- Assignment (`=`): Assigns a value to a variable.
- Add and assign (`+=`): Adds the right operand to the left operand and assigns the result.
- Subtract and assign (`-=`): Subtracts the right operand from the left operand and assigns the result.
- Multiply and assign (`*=`): Multiplies the left operand by the right operand and assigns the result.
- Divide and assign (`/=`): Divides the left operand by the right operand and assigns the result.
- Modulus and assign (`%=`): Takes the modulus using two operands and assigns the result.

Example:
using System;

class Program
{
    static void Main()
    {
        int a = 5;
        a += 3; // a = a + 3
        Console.WriteLine("a after +=: " + a); // Output: 8
        a -= 2; // a = a - 2
        Console.WriteLine("a after -=: " + a); // Output: 6
        a *= 2; // a = a * 2
        Console.WriteLine("a after *=: " + a); // Output: 12
        a /= 4; // a = a / 4
        Console.WriteLine("a after /=: " + a); // Output: 3
        a %= 2; // a = a % 2
        Console.WriteLine("a after %=: " + a); // Output: 1
    }
}

Output:
a after +=: 8
a after -=: 6
a after *=: 12
a after /=: 3
a after %=: 1

6. Unary Operators

These operators operate on a single operand.

- Increment (`++`): Increases the value of the operand by 1.
- Decrement (`--`): Decreases the value of the operand by 1.
- Unary plus (`+`): Indicates a positive value (often redundant).
- Unary minus (`-`): Negates the value.

Example:
using System;

class Program
{
    static void Main()
    {
        int a = 5;
        Console.WriteLine("Initial a: " + a); // Output: 5
        Console.WriteLine("Post-increment: " + a++); // Output: 5
        Console.WriteLine("After post-increment: " + a); // Output: 6
        Console.WriteLine("Pre-increment: " + ++a); // Output: 7
        Console.WriteLine("Post-decrement: " + a--); // Output: 7
        Console.WriteLine("After post-decrement: " + a); // Output: 6
        Console.WriteLine("Pre-decrement: " + --a); // Output: 5
    }
}

Output:
Initial a: 5
Post-increment: 5
After post-increment: 6
Pre-increment: 7
Post-decrement: 7
After post-decrement: 6
Pre-decrement: 5

7. Ternary Operator

The ternary operator is a shorthand for an `if-else` statement.

Syntax: `condition ? expression_if_true : expression_if_false`

Example:
using System;

class Program
{
    static void Main()
    {
        int a = 5;
        string result = (a > 3) ? "a is greater than 3" : "a is less than or equal to 3";
        Console.WriteLine(result); // Output: a is greater than 3
    }
}

Output:
a is greater than 3

8. Null Coalescing Operator

The null coalescing operator is used to define a default value for nullable types.

Syntax: `variable ?? default_value`

Example:
using System;

class Program
{
    static void Main()
    {
        string message = null;
        string result = message ?? "Default message";
        Console.WriteLine(result); // Output: Default message
    }
}

Output:
Default message

9. Type Testing and Casting Operators

These operators are used to check or convert data types. - `is`: Checks if an object is of a specific type.
- `as`: Attempts to cast an object to a specific type, returning null if unsuccessful.

Example:
using System;

class Program
{
    static void Main()
    {
        object obj = "Hello, world!";
        if (obj is string str)
        {
            Console.WriteLine("String value: " + str); // Output: Hello, world!
        }

        object obj2 = null;
        string result = obj2 as string;
        Console.WriteLine(result == null ? "obj2 is null" : result); // Output: obj2 is null
    }
}

Output:
String value: Hello, world!
obj2 is null

10. Lambda Operators

These operators are used in LINQ and other functional programming features.

- Lambda Expression (`=>`): Represents a method that takes parameters and returns a value.

Example:
using System;
using System.Linq;

class Program
{
    static void Main()
    {
        var numbers = new[] { 1, 2, 3, 4, 5 };
        var squares = numbers.Select(n => n * n);
        Console.WriteLine(string.Join(", ", squares)); // Output: 1, 4, 9, 16, 25
    }
}

Output:
1, 4, 9, 16, 25

Summary
C# operators are versatile and powerful tools that facilitate a wide range of operations on data. Understanding their usage is essential for effective programming in C#.

Previous: C# Datatypes | Next: C# Methods

<
>