Utilizor
Contact Us

C# Operators

Arithmetic, Assignment, Comparison, Logical.

C# Operators

Operators are used to perform operations on variables and values.

In the example below, we use the + operator to add together two values:

int x = 100 + 50;

Arithmetic Operators

Used to perform common mathematical operations (+, -, *, /, %, ++, --).

Assignment Operators

Used to assign values to variables (=, +=, -=, *=, /=).

Comparison Operators

Used to compare two values (==, !=, >, <, >=, <=).

Logical Operators

Used to determine the logic between variables or values (&&, ||, !).

Examples

Arithmetic Operators

Addition, multiplication, division, modulus.

using System;

class Program
{
  static void Main(string[] args)
  {
    int salary = 5000;
    int bonus = 1000;
    Console.WriteLine(salary + bonus);
    Console.WriteLine(salary * 2);
    Console.WriteLine(salary / 2);
    Console.WriteLine(salary % 3);
  }
}

Assignment Operators

Using += assignment operator.

using System;

class Program
{
  static void Main(string[] args)
  {
    int x = 10;
    x += 5;
    Console.WriteLine(x);
  }
}

Comparison Operators

Comparing two values.

using System;

class Program
{
  static void Main(string[] args)
  {
    int x = 5;
    int y = 3;
    Console.WriteLine(x > y); // returns True because 5 is greater than 3
  }
}

Logical Operators

Using && (AND) operator.

using System;

class Program
{
  static void Main(string[] args)
  {
    int x = 5;
    Console.WriteLine(x > 3 && x < 10); // returns True because 5 is greater than 3 AND 5 is less than 10
  }
}

Increment/Decrement

Using ++ and -- operators.

using System;

class Program
{
    static void Main()
    {
        int x = 10;
        x++;
        Console.WriteLine(x);
        x--;
        Console.WriteLine(x);
    }
}