Basics

C# Operators

C# Operators

C# operators include arithmetic and null-coalescing operators.

Introduction to C# Operators

Operators in C# are special symbols or keywords that perform operations on operands. They are essential to manipulating data and variables in your code. Understanding operators is crucial for performing calculations, making decisions, and more.

Arithmetic Operators

Arithmetic operators in C# are used to perform basic mathematical operations. These include addition, subtraction, multiplication, division, and modulus.

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

Null-Coalescing Operator

The null-coalescing operator (??) is used to define a default value when working with nullable types. It returns the left-hand operand if it is not null, otherwise, it evaluates the right-hand operand.

Compound Assignment Operators

Compound assignment operators provide a shorthand way to apply arithmetic operations and assign the result to the variable. They combine an arithmetic operation with an assignment.

  • += : Adds the right operand to the left operand and assigns the result to the left operand.
  • -= : Subtracts the right operand from the left operand and assigns the result to the left operand.
  • *= : Multiplies the left operand by the right operand and assigns the result to the left operand.
  • /= : Divides the left operand by the right operand and assigns the result to the left operand.
  • %= : Takes modulus of left operand by the right operand and assigns the result to the left operand.

Comparison Operators

Comparison operators are used to compare two values. They return a boolean value (true or false) depending on the condition being evaluated.

  • == : Checks if two operands are equal.
  • != : Checks if two operands are not equal.
  • > : Checks if the left operand is greater than the right.
  • < : Checks if the left operand is less than the right.
  • >= : Checks if the left operand is greater than or equal to the right.
  • <= : Checks if the left operand is less than or equal to the right.

Logical Operators

Logical operators are used to combine conditional statements. They operate on boolean values and return a boolean result.

  • && : Logical AND operator. Returns true if both operands are true.
  • || : Logical OR operator. Returns true if at least one of the operands is true.
  • ! : Logical NOT operator. Inverts the value of a boolean operand.