Operators are special symbols that perform operations on operands (variables and values). C# supports a wide range of operators to perform various operations, including arithmetic, logical, relational, bitwise, assignment, and more. Understanding these operators is crucial for effective programming in C#.
Arithmetic operators perform mathematical calculations.
Operator | Description | Example |
---|---|---|
+ | Addition | a + b |
- | Subtraction | a - b |
* | Multiplication | a * b |
/ | Division | a / b |
% | Modulus (remainder) | a % b |
++ | Increment (by 1) | a++ or ++a |
-- | Decrement (by 1) | a-- or --a |
using System;
namespace ArithmeticOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
int sum = a + b;
int difference = a - b;
int product = a * b;
int quotient = a / b;
int remainder = a % b;
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Difference: {difference}");
Console.WriteLine($"Product: {product}");
Console.WriteLine($"Quotient: {quotient}");
Console.WriteLine($"Remainder: {remainder}");
}
}
using System;
namespace ArithmeticOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
int c = 3;
// Combined arithmetic operations
int result = a + b * c - (a / c) + (b % c);
Console.WriteLine($"Result: {result}");
// Increment and decrement operations
int x = 10;
Console.WriteLine($"Initial x: {x}");
Console.WriteLine($"x++: {x++}");
Console.WriteLine($"++x: {++x}");
Console.WriteLine($"x--: {x--}");
Console.WriteLine($"--x: {--x}");
}
}
Relational operators compare two values and return a boolean result (true or false).
Operator | Description | Example |
---|---|---|
== | Equal to | a == b |
!= | Not equal to | a != b |
> | Greater than | a > b |
< | Less than | a < b |
>= | Greater than or equal to | a >= b |
<= | Less than or equal to | a <= b |
using System;
namespace RelationalOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
bool isEqual = a == b;
bool isNotEqual = a != b;
bool isGreaterThan = a > b;
bool isLessThan = a < b;
bool isGreaterThanOrEqual = a >= b;
bool isLessThanOrEqual = a <= b;
Console.WriteLine($"a == b: {isEqual}");
Console.WriteLine($"a != b: {isNotEqual}");
Console.WriteLine($"a > b: {isGreaterThan}");
Console.WriteLine($"a < b: {isLessThan}");
Console.WriteLine($"a >= b: {isGreaterThanOrEqual}");
Console.WriteLine($"a <= b: {isLessThanOrEqual}");
}
}
using System;
namespace RelationalOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
int c = 10;
// Combining relational operations with logical operators
bool result1 = (a > b) && (a == c);
bool result2 = (a < b) || (b <= c);
bool result3 = !(a != c);
Console.WriteLine($"(a > b) && (a == c): {result1}");
Console.WriteLine($"(a < b) || (b <= c): {result2}");
Console.WriteLine($"!(a != c): {result3}");
}
}
Logical operators perform logical operations on boolean values and return a boolean result.
Operator | Description | Example |
---|---|---|
&& | Logical AND | a && b |
|| | Logical OR | a || b |
! | Logical NOT | !a |
using System;
namespace LogicalOperators
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = false;
bool andResult = a && b;
bool orResult = a || b;
bool notResult = !a;
Console.WriteLine($"a && b: {andResult}");
Console.WriteLine($"a || b: {orResult}");
Console.WriteLine($"!a: {notResult}");
}
}
using System;
namespace LogicalOperators
class Program
{
static void Main(string[] args)
{
bool a = true;
bool b = false;
bool c = true;
// Combining logical operators with relational operators
bool result1 = (a && b) || c;
bool result2 = !(a && (b || c));
Console.WriteLine($"(a && b) || c: {result1}");
Console.WriteLine($"!(a && (b || c)): {result2}");
}
}
Bitwise operators perform bit-level operations on integer types.
Operator | Description | Example |
---|---|---|
& | Bitwise AND | a & b |
| | Bitwise OR | a | b |
^ | Bitwise XOR | a ^ b |
~ | Bitwise NOT | ~a |
<< | Left shift | a << b |
>> | Right shift | a >> b |
using System;
namespace BitwiseOperators
class Program
{
static void Main(string[] args)
{
int a = 5; // 0101 in binary
int b = 3; // 0011 in binary
int andResult = a & b; // 0001 in binary
int orResult = a | b; // 0111 in binary
int xorResult = a ^ b; // 0110 in binary
int notResult = ~a; // 1111...1010 in binary (two's complement representation)
int leftShiftResult = a << 1; // 1010 in binary
int rightShiftResult = a >> 1; // 0010 in binary
Console.WriteLine($"a & b: {andResult}");
Console.WriteLine($"a | b: {orResult}");
Console.WriteLine($"a ^ b: {xorResult}");
Console.WriteLine($"~a: {notResult}");
Console.WriteLine($"a << 1: {leftShiftResult}");
Console.WriteLine($"a >> 1: {rightShiftResult}");
}
}
using System;
namespace BitwiseOperators
class Program
{
static void Main(string[] args)
{
int a = 12; // 1100 in binary
int b = 25; // 11001 in binary
// Combining bitwise operators with arithmetic operations
int result1 = (a & b) + (a | b);
int result2 = (a ^ b) - (~b);
int result3 = (a << 2) + (b >> 2);
Console.WriteLine($"(a & b) + (a | b): {result1}");
Console.WriteLine($"(a ^ b) - (~b): {result2}");
Console.WriteLine($"(a << 2) + (b >> 2): {result3}");
}
}
Assignment operators assign values to variables.
Operator | Description | Example |
---|---|---|
= | Assign | a = b |
+= | Add and assign | a += b |
-= | Subtract and assign | a -= b |
*= | Multiply and assign | a *= b |
/= | Divide and assign | a /= b |
%= | Modulus and assign | a %= b |
&= | Bitwise AND and assign | a &= b |
|= | Bitwise OR and assign | a |= b |
^= | Bitwise XOR and assign | a ^= b |
<<= | Left shift and assign | a <<= b |
>>= | Right shift and assign | a >>= b |
using System;
namespace AssignmentOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
a += b; // a = a + b
Console.WriteLine($"a += b: {a}");
a -= b; // a = a - b
Console.WriteLine($"a -= b: {a}");
a *= b; // a = a * b
Console.WriteLine($"a *= b: {a}");
a /= b; // a = a / b
Console.WriteLine($"a /= b: {a}");
a %= b; // a = a % b
Console.WriteLine($"a %= b: {a}");
}
}
using System;
namespace AssignmentOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 5;
int c = 3;
a += b * c; // a = a + (b * c)
Console.WriteLine($"a += b * c: {a}");
a -= b / c; // a = a - (b / c)
Console.WriteLine($"a -= b / c: {a}");
a *= b % c; // a = a * (b % c)
Console.WriteLine($"a *= b % c: {a}");
a /= b + c; // a = a / (b + c)
Console.WriteLine($"a /= b + c: {a}");
a %= b - c; // a = a % (b - c)
Console.WriteLine($"a %= b - c: {a}");
}
}
The conditional operator `? :` is a ternary operator that returns one of two values depending on the value of a Boolean expression.
Operator | Description | Example |
---|---|---|
? : | Conditional | condition ? value_if_true : value_if_false |
using System;
namespace ConditionalOperator
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
// Basic usage of conditional operator
string result = (a > b) ? "a is greater than b" : "a is less than or equal to b";
Console.WriteLine(result);
}
}
using System;
namespace ConditionalOperator
class Program
{
static void Main(string[] args)
{
int a = 10;
int b = 20;
int c = 5;
// Nested conditional operators
string result = (a > b) ? "a is greater than b" :
(b > c) ? "b is greater than c" :
"c is the greatest";
Console.WriteLine(result);
}
}
Null-coalescing operators provide a convenient way to handle null values.
Operator | Description | Example |
---|---|---|
?? | Null-coalescing | a ?? b |
??= | Null-coalescing assignment | a ??= b |
using System;
namespace NullCoalescingOperators
class Program
{
static void Main(string[] args)
{
string name = null;
string defaultName = "Default";
// Using null-coalescing operator
string finalName = name ?? defaultName;
Console.WriteLine($"Name: {finalName}");
}
}
using System;
namespace NullCoalescingOperators
class Program
{
static void Main(string[] args)
{
string[] names = { null, "John", "Doe" };
string defaultName = "Default";
foreach (var name in names)
{
// Using null-coalescing assignment operator
string finalName = name ??= defaultName;
Console.WriteLine($"Name: {finalName}");
}
}
}
C# provides several other operators for specific purposes.
Operator | Description | Example |
---|---|---|
`is` | Type compatibility | a is Type |
`as` | Type conversion | a as Type |
`sizeof` | Returns the size of a type | sizeof(Type) |
`typeof` | Returns the System.Type object for a type | typeof(Type) |
`nameof` | Returns the name of a variable, type, or member as a string | nameof(variable) |
`checked` | Checks for arithmetic overflow | checked(expression) |
`unchecked` | Suppresses overflow-checking | unchecked(expression) |
`default` | Returns the default value of a type | default(Type) |
using System;
namespace MiscellaneousOperators
class Program
{
static void Main(string[] args)
{
int a = 10;
Type type = typeof(int);
bool isInt = a is int;
Console.WriteLine($"Type of a: {type}");
Console.WriteLine($"a is int: {isInt}");
}
}
using System;
namespace MiscellaneousOperators
class Program
{
static void Main(string[] args)
{
object obj = "Hello, world!";
string str = obj as string;
Console.WriteLine($"String: {str}");
// Using nameof and default operators
Console.WriteLine($"Name of variable: {nameof(obj)}");
int defaultValue = default(int);
Console.WriteLine($"Default value of int: {defaultValue}");
}
}
C# allows you to define custom behavior for operators in your own classes or structs.
Example:
using System;
namespace OperatorOverloading
class Complex
{
public int Real { get; set; }
public int Imaginary { get; set; }
public Complex(int real, int imaginary)
{
Real = real;
Imaginary = imaginary;
}
// Overloading the + operator
public static Complex operator +(Complex c1, Complex c2)
{
return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
}
public override string ToString()
{
return $"{Real} + {Imaginary}i";
}
}
class Program
{
static void Main(string[] args)
{
Complex c1 = new Complex(1, 2);
Complex c2 = new Complex(3, 4);
Complex result = c1 + c2;
Console.WriteLine($"Result: {result}");
}
}
Understanding and applying operators correctly is crucial for writing efficient and effective C# code. This tutorial covered various types of operators with examples to help you grasp their usage and best practices.