c sharp Logo

C# Operators


Arithmetic Operators

Arithmetic operators perform mathematical operations on numbers. The following are the arithmetic operators in C#:

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

Example:

int number1 = 10;

int number2 = 5;

 

int sum = number1 + number2;

int difference = number1 - number2;

int product = number1 * number2;

int quotient = number1 / number2;

int remainder = number1 % number2;

 

Console.WriteLine("Sum: " + sum);

Console.WriteLine("Difference: " + difference);

Console.WriteLine("Product: " + product);

Console.WriteLine("Quotient: " + quotient);

Console.WriteLine("Remainder: " + remainder);

 

Assignment Operators

Assignment operators assign values to variables. The following are the assignment operators in C#:

  • =: Assignments a value to a variable
  • +=: Adds a value to a variable
  • -=: Subtracts a value from a variable
  • *=: Multiplies a value to a variable
  • /=: Divides a variable by a value
  • %=: Assigns the modulus (remainder) of a division to a variable

Example:

int number = 10;

 

number += 5;

number -= 2;

number *= 3;

number /= 4;

number %= 3;

 

Console.WriteLine("Number: " + number);

 

Comparison Operators

Comparison operators compare two values. The following are the comparison operators in C#:

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

Example:

int number1 = 10;

int number2 = 5;

 

bool isEqual = (number1 == number2);

bool isNotEqual = (number1 != number2);

bool isLessThan = (number1 < number2);

bool isLessThanOrEqual = (number1 <= number2);

bool isGreaterThan = (number1 > number2);

bool isGreaterThanOrEqual = (number1 >= number2);

 

Console.WriteLine("Is Equal: " + isEqual);

Console.WriteLine("Is Not Equal: " + isNotEqual);

Console.WriteLine("Is Less Than: " + isLessThan);

Console.WriteLine("Is Less Than or Equal: " + isLessThanOrEqual);

Console.WriteLine("Is Greater Than: " + isGreaterThan);

Console.WriteLine("Is Greater Than or Equal: " + isGreaterThanOrEqual);

 

Logical Operators

Logical operators combine boolean values to form new boolean values. The following are the logical operators in C#:

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

Example:

bool isStudent = true;

bool isAdult = true;

 

bool isStudentAndAdult = (isStudent && isAdult);

bool isStudentOrAdult = (isStudent || isAdult);

bool isNotStudent = !isStudent;

 

Console.WriteLine("Is Student and Adult: " + isStudentAndAdult);

Console.WriteLine("Is Student or Adult: " + isStudentOrAdult);

Console.WriteLine("Is Not Student: " + isNotStudent);