C# Operators Intro

Operators in C# are special symbols used to perform operations on variables and values. They help you perform tasks like arithmetic calculations, value assignments, logical comparisons, and bit manipulations. C# supports different types of operators:

Key Topics

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical operations:

  • +: Addition
  • -: Subtraction
  • *: Multiplication
  • /: Division
  • %: Modulus

2. Assignment Operators

Assignment operators assign values to variables:

  • =: Assign
  • +=: Add and assign
  • -=: Subtract and assign
  • *=: Multiply and assign
  • /=: Divide and assign

3. Comparison Operators

Comparison operators compare values and return a boolean result:

  • ==: Equal to
  • !=: Not equal to
  • >: Greater than
  • <: Less than
  • >=: Greater than or equal to
  • <=: Less than or equal to

4. Logical Operators

Logical operators combine conditional expressions:

  • &&: Logical AND
  • ||: Logical OR
  • !: Logical NOT

5. Bitwise Operators

Bitwise operators perform bit-level operations:

  • &: AND
  • |: OR
  • ^: XOR
  • ~: NOT
  • <<: Left shift
  • >>: Right shift

6. Conditional (Ternary) Operator

The conditional operator ?: is a shorthand for if-else:

  • condition ? trueExpression : falseExpression

7. Null-Coalescing Operator

The null-coalescing operator ?? returns the left operand if it's not null, otherwise, the right operand:

  • a ?? b

8. Increment and Decrement Operators

These operators increase or decrease the value of a variable by 1:

  • ++: Increment
  • --: Decrement

9. Type Operators

Type operators check or cast types:

  • is: Checks if an object is of a certain type
  • as: Attempts to cast an object to a specific type

10. Await Operator

The await operator pauses method execution until the awaited task completes, used in asynchronous programming.

11. Pointer Operators

Pointers allow direct memory manipulation. They are used in unsafe code:

  • *: Dereference pointer
  • &: Address-of operator
  • ->: Pointer member access

Key Takeaways

  • Arithmetic Operators: Perform mathematical operations.
  • Assignment Operators: Assign values to variables.
  • Comparison Operators: Compare values and return boolean.
  • Logical Operators: Combine boolean expressions.
  • Bitwise Operators: Operate at the bit level.
  • Ternary Operator: Shorthand for conditional logic.