Operators in C#
Operators in C# are special symbols or keywords used to perform operations on variables and values. C# supports a rich set of operators, including arithmetic, comparison, logical, assignment, and more. Understanding how these operators work is crucial for writing logical and efficient code.
Example
using System;
class Program
{
static void Main()
{
int a = 10;
int b = 5;
// Arithmetic Operators
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));
// Comparison Operators
Console.WriteLine("Is a > b? " + (a > b));
Console.WriteLine("Is a == b? " + (a == b));
// Logical Operators
bool x = true, y = false;
Console.WriteLine("x && y: " + (x && y));
Console.WriteLine("x || y: " + (x || y));
Console.WriteLine("!x: " + (!x));
}
}
Summary
Operators form the backbone of any programming language. In C#, operators are categorized into several types like arithmetic, comparison, logical, and assignment operators. Mastering these helps in implementing conditions, calculations, and logic efficiently.
Example
int number = 10;
// Assignment Operators
number += 5; // Same as number = number + 5
Console.WriteLine(number); // Output: 15