Learn c#
  • Overview
  • Chapter 0 c# vs .net
  • Chapter 1 Definitions
    • Data Types (Primitive Types)
    • Variables
    • Overflow
    • Identifiers
    • Comments
  • Chapter 2 Type Conversions
  • Chapter 3 C# Operators
  • Chapter 4 Non-Primitive Types
    • Reference Types and value types
    • Class, Fields, property
    • Structs and Arrays
    • Strings
    • Enums
  • Chapter 5 Conditional statements and Loops
    • Conditional Statements
    • Random Class
  • External Links
    • cSharp-Station
    • cSharp corner
    • CodeProject
    • cSharp Guide by Microsoft
  • Tips
Powered by GitBook
On this page

Chapter 3 C# Operators

We have 5 types of operators in c#:

  • Arithmetic Operators

  • Comparison Operators

  • Assignment Operators

  • Logical Operators

  • Bitwise Operators

Arithmetic Operators: Add, subtract, multiply, divide, and remainder.

We also have increment and decrement operators, which would add or remove values.

Incrementing Values:

int x=5; //assigns x value as 5

x = x + 1; //increments x value by adding 1 to it so x = 6

x+=1;// x=7 same as above statement

x++; x = 8

all above statements add 1 to x value.

int y = ++x; // increment x and assign it to y. y=9, x=9 here.

int y = x++; //assign value x to y, and increment x value. y=9, x=10 here.

Decrementing Values:

x = x-1;

x-=1;

x–-;

int y = –x;

y=x–;

All work same as incrementing expressions shown above but these expressions will decrease values.

Comparison Operators:

Equal ==, Not Equal !=, Greater than >, Greater than or equal to >=, less than <, less than or equal to <=.

Ex:

int a = 10;

int b = 2;

int c = 3;

console.writeline(a>b); //output would be true.

console.writeline(!(a>b));//output false

You can also add complex statements like console.writeline(!(a>b) &&(b>c))//output true.

Assignment Operators:

Assignment =, Addition assignment +=, Subtraction assignment -=, multiplication assignment *=, division assignment /=

Logical Operators: These are used in boolean operators, in condition statements.

And &&, Or ||, Not !

Logical AND:

Let’s assume we have two variables: x and y. In C#, the logical AND operator is indicated by &&.

Boolean expressions are defined as:

z = x && y

In this expression, z is true if both x and y are true; otherwise, it’ll be false.

Logical OR:

In C#, logical OR is indicated by two vertical lines (||). Considering the following expression:

a = x || y

a will be true, if either x or y is true.

Logical NOT

The NOT operator in C# is indicated by an exclamation mark (!) and it reverses the value of a

given variable or expression:

y = !x

So, here, if x is true, y will be false, and if x is false, y will be true.

Bitwise Operators: These are used in low level operations.

And &, or |

c# uses BODMAS rule while evaluating equations like a+b*c

PreviousChapter 2 Type ConversionsNextChapter 4 Non-Primitive Types

Last updated 6 years ago