Mark As Completed Discussion

Operators and Expressions

In C#, operators are used to perform various operations on variables and values. They allow you to perform arithmetic calculations, compare values, and perform logical operations.

Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations. C# provides the following arithmetic operators:

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

Here's an example of using arithmetic operators:

TEXT/X-CSHARP
1int x = 10;
2int y = 5;
3
4int addition = x + y;
5int subtraction = x - y;
6int multiplication = x * y;
7int division = x / y;
8int modulus = x % y;
9
10Console.WriteLine("Addition: " + addition);
11Console.WriteLine("Subtraction: " + subtraction);
12Console.WriteLine("Multiplication: " + multiplication);
13Console.WriteLine("Division: " + division);
14Console.WriteLine("Modulus: " + modulus);

Comparison Operators

Comparison operators are used to compare two values and determine the relationship between them. C# provides the following comparison operators:

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

Here's an example of using comparison operators:

TEXT/X-CSHARP
1int x = 10;
2int y = 5;
3
4bool isEqual = x == y;
5bool isNotEqual = x != y;
6bool isGreater = x > y;
7bool isLess = x < y;
8bool isGreaterOrEqual = x >= y;
9bool isLessOrEqual = x <= y;
10
11Console.WriteLine("Is Equal: " + isEqual);
12Console.WriteLine("Is Not Equal: " + isNotEqual);
13Console.WriteLine("Is Greater: " + isGreater);
14Console.WriteLine("Is Less: " + isLess);
15Console.WriteLine("Is Greater or Equal: " + isGreaterOrEqual);
16Console.WriteLine("Is Less or Equal: " + isLessOrEqual);

Logical Operators

Logical operators are used to perform logical operations on boolean values. C# provides the following logical operators:

  • AND (&&)
  • OR (||)
  • NOT (!)

Here's an example of using logical operators:

TEXT/X-CSHARP
1bool isTrue = true;
2bool isFalse = false;
3
4bool andResult = isTrue && isFalse;
5bool orResult = isTrue || isFalse;
6bool notResult = !isTrue;
7
8Console.WriteLine("AND Result: " + andResult);
9Console.WriteLine("OR Result: " + orResult);
10Console.WriteLine("NOT Result: " + notResult);

Understanding and using operators correctly is an essential part of writing efficient and logical code in C#.

C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment