Operators

Operators allow us to perform various operations on operands. There are various operators in C# to perform different types of operations.

1. Arithmetic Operators:

These are mathematical operators used on operands. Examples include:
  • Addition (+): adds two operands (e.g. x + y)
  • Subtraction (-): subtracts the second operand from the first (e.g. x – y)
  • Multiplication (*): multiplies two operands (e.g. x * y)
  • Division (/): divides the first operand by the second (e.g. x / y)
  • Modulus (%): returns the remainder when dividing the first operand by the second (e.g. x % y)

2. Relational Operators:

Comparison operators are used to compare values and return a boolean result. Some common operators include equality (==), inequality (!=), greater than (>), less than (<), greater than or equal to (>=), and less than or equal to (<=).
Example
int a = 100;
int b = 200;
Console.WriteLine(a < b); // returns True

3. Logical Operators:

Used for combining conditions.
  • AND (&&): Returns true if both operands are true.
  • OR (||): Returns true if at least one operand is true.
  • NOT (!): Negates the value of an operand.
Example
using System;

namespace MyTest
{
  class Program
  {
    static void Main(string[] args)
    {
      int a = 10;
      Console.WriteLine(a > 5 && a < 20); // returns True 
     }
  }
}

4. Assignment Operators:

Assign values to variables (e.g., int x = 20;).

5. Bitwise Operators:

Perform operations on individual bits using AND (&), OR (|), XOR (^), NOT (~), Left Shift (<<), and Right Shift (>>).
using System;

namespace MyTest

class Test
{
    static void Main(string[] args)
  {
         int a = 10, b = 20, output;

            // Bitwise AND (&) Operator
            output = a & b;
            Console.WriteLine("Bitwise AND: " + output);

            // Bitwise OR (|) Operator
            output = a | b;
            Console.WriteLine("Bitwise OR: " + output);

            // Bitwise XOR (^) Operator
            output = a ^ b;
            Console.WriteLine("Bitwise XOR: " + output);
  }
}
}

6. Unary Operators:

These operators work with a single operand:
  • Increment (++): Increases the value of an integer. Pre-increment (++x) updates instantly; post-increment (x++) preserves value temporarily.
  • Decrement (–): Decreases the value of an integer. Pre-decrement (–x) updates instantly; post-decrement (x–) preserves value temporarily.
Example
using System;

namespace MyTest
{
  class Program
  {
    static void Main(string[] args)
    {
      int x = 10;
      x++;
      Console.WriteLine(x);  //result - 11
     }
  }
}
Post a comment

Leave a Comment

Scroll to Top