Operators in C# Programming
Introduction
Operators in C# are symbols that perform operations on variables and values. This tutorial covers arithmetic, relational, logical, and bitwise operators with examples to demonstrate their usage.
Arithmetic Operators
Arithmetic operators are used for basic mathematical calculations.
+
: Addition-
: Subtraction*
: Multiplication/
: Division%
: Modulus (remainder)
Example: Arithmetic Operators
using System; class Program { static void Main() { int a = 10, b = 3; Console.WriteLine("Addition: " + (a + b)); Console.WriteLine("Subtraction: " + (a - b)); Console.WriteLine("Multiplication: " + (a * b)); Console.WriteLine("Division: " + (a / b)); Console.WriteLine("Modulus: " + (a % b)); } }
Relational Operators
Relational operators compare two values and return a boolean result (true
or false
).
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
Example: Relational Operators
using System; class Program { static void Main() { int x = 5, y = 10; Console.WriteLine("x == y: " + (x == y)); Console.WriteLine("x != y: " + (x != y)); Console.WriteLine("x > y: " + (x > y)); Console.WriteLine("x < y: " + (x < y)); Console.WriteLine("x >= y: " + (x >= y)); Console.WriteLine("x <= y: " + (x <= y)); } }
Logical Operators
Logical operators are used to perform logical operations.
&&
: Logical AND||
: Logical OR!
: Logical NOT
Example: Logical Operators
using System; class Program { static void Main() { bool condition1 = true; bool condition2 = false; Console.WriteLine("condition1 && condition2: " + (condition1 && condition2)); Console.WriteLine("condition1 || condition2: " + (condition1 || condition2)); Console.WriteLine("!condition1: " + (!condition1)); } }
Bitwise Operators
Bitwise operators perform operations at the binary level.
&
: Bitwise AND|
: Bitwise OR^
: Bitwise XOR~
: Bitwise complement<<
: Left shift>>
: Right shift
Example: Bitwise Operators
using System; class Program { static void Main() { int m = 5; // Binary: 0101 int n = 3; // Binary: 0011 Console.WriteLine("Bitwise AND: " + (m & n)); // Binary: 0001 Console.WriteLine("Bitwise OR: " + (m | n)); // Binary: 0111 Console.WriteLine("Bitwise XOR: " + (m ^ n)); // Binary: 0110 Console.WriteLine("Bitwise complement of m: " + (~m)); // Binary: 1010 (2's complement) Console.WriteLine("Left shift m by 1: " + (m << 1)); // Binary: 1010 Console.WriteLine("Right shift m by 1: " + (m >> 1)); // Binary: 0010 } }
Conclusion
C# provides a variety of operators to perform arithmetic, relational, logical, and bitwise operations. Understanding these operators and practicing with examples will help you write efficient and logical code.