Operators in C#
In C#, Operators are special types of symbols which perform operations on variables or values. It is a fundamental part of language which plays an important role in performing different mathematical operations. It takes one or more operands and performs operations to produce a result.
Types of Operators 运算符员类型
C# has some set of operators that can be classified into various categories based on their functionality. Categorized into the following types:
- Arithmetic Operators 算术运算符
- Relational Operators 关系运算符
- Logical Operators 逻辑运算符
- Assignment Operators 赋值运算符
- Increment and Decrement Operators 递增和递减运算符
- Bitwise Operators 位运算符
- Ternary Operator 三元运算符
- Null Coalescing Operator 零合并算子
Arithmetic Operators 算术运算符
Arithmetic operators are used to perform basic mathematical operations on numeric values.
- Addition ( + ) 加号(+)
- Subtraction ( - ) 减法(-)
- Multiplication ( * ) 乘法(*)
- Division ( / ) 分配 ( / )
- Modulus ( % ) 取模(%)
Example:
using System;
class Geeks
{
static void Main(string[] args)
{
int x = 8, y = 4;
// Using different arithmetic operators
Console.WriteLine("Addition: " + (x + y));
Console.WriteLine("Subtraction: " + (x - y));
Console.WriteLine("Multiplication: " + (x * y));
Console.WriteLine("Division: " + (x / y));
Console.WriteLine("Modulo: " + (x % y));
}
}
Output
Addition: 12
Subtraction: 4
Multiplication: 32
Division: 2
Modulo: 0
Relational Operators 关系运算符
Relational operators are used to compare values. And we get the answer in either true or false ( boolean). Let’s learn about different relation operators.
- Equal to ( == )
- Not equal to ( != )
- Less than ( < )
- Less than or equal to ( <= )
- Greater than ( > )
- Greater than or equal to ( >= )
Example:
using System;
class Geeks
{
static void Main(string[] args)
{
int x = 10, y = 20;
// Compare using different relational operators
Console.WriteLine(x == y);
Console.WriteLine(x != y);
Console.WriteLine(x > y);
Console.WriteLine(x < y);
Console.WriteLine(x >= y);
Console.WriteLine(x <= y);
}
}
Output
False
True
False
True
False
True
Logical Operators 逻辑运算符
Used when multiple conditions and there we can combine these to compare complex conditions.
- Logical AND (&&) : returns true when both conditions are true.
- Logical OR ( || ) : returns true if at least one condition is true.
- Logical NOT ( ! ): returns true when a condition is false and vice-versa.
Example:
using System;
class Geeks
{
static void Main(string[] args)
{
bool a = true, b = false;
// conditional operators
if (a && b)
Console.WriteLine("a and b are true");
if (a || b)
Console.WriteLine("Either a or b is true");
if (!a)
Console.WriteLine("a is not true");
if (!b)
Console.WriteLine("b is not true");
}
}
Output
Either a or b is true
b is not true
Assignment Operators 赋值运算符
Assignment operators are used to assign values to variables. The assignment operator is combined with others to create shorthand compound statements. Common compound operators include:
- += (Add and assign.)
- -= (Subtract and assign.)
- *= (Multiply and assign.)
- /= (Divide and assign.)
- %= (Modulo and assign.)
Example:
using System;
class Geeks
{
static void Main(string[] args)
{
int a = 10;
// Using different assignment operators
a += 5;
Console.WriteLine("Add Assignment: " + a);
a -= 3;
Console.WriteLine("Subtract Assignment: " + a);
a *= 2;
Console.WriteLine("Multiply Assignment: " + a);
a /= 4;
Console.WriteLine("Division Assignment: " + a);
a %= 5;
Console.WriteLine("Modulo Assignment: " + a);
}
}
Output
Add Assignment: 15
Subtract Assignment: 12
Multiply Assignment: 24
Division Assignment: 6
Modulo Assignment: 1
Increment and Decrement Operators 递增和递减运算符
Increment and decrement operators are used to increase or decrease the value of a variable by 1.
++ (Increments by 1)
- Post-Increment: Uses value first, then increments.
- Pre-Increment: Increments first, then uses value.
– (Decrements by 1)
- Post-Decrement: Uses value first, then decrements.
- Pre-Decrement: Decrements first, then uses the value.
Example:
using System;
public class Geeks
{
static public void Main()
{
int a = 5;
// pre-increment
Console.WriteLine("++a returns: " + ++a);
// post-increment
Console.WriteLine("a++ returns: " + a++);
Console.WriteLine("Final value of a: " + a);
Console.WriteLine();
// pre-decrement
Console.WriteLine("--a returns: " + --a);
// post-decrement
Console.WriteLine("a-- returns: " + a--);
Console.WriteLine("Final value of a: " + a);
}
}
Output
++a returns: 6
a++ returns: 6
Final value of a: 7
--a returns: 6
a-- returns: 6
Final value of a: 5
Bitwise Operators 位运算符
Bitwise operators are used to perform bit-level operations on integer values. It takes less time because it directly works on the bits.
Example:
using System;
class Geeks
{
static void Main(string[] args)
{
// Binary representation: 1010
int x = 10;
// Binary representation: 0010
int y = 2;
// Bitwise AND
Console.WriteLine(x & y);
// Bitwise OR
Console.WriteLine(x | y);
// Bitwise XOR
Console.WriteLine(x ^ y);
// Bitwise NOT
Console.WriteLine(~x);
// Shifting bit by one on the left
Console.WriteLine(x << 1);
// Shifting bit by one on the right
Console.WriteLine(x >> 1);
}
}
Output
1
7
6
-6
10
2
Ternary Operator 三元运算符
The ternary operator is a shorthand for an if-else statement. It evaluates a condition and returns one of two values depending on whether the condition is true or false.
Syntax
condition ? if true : if false
Example:
using System;
public class Geeks
{
static public void Main()
{
int a = 10, b = 5;
// similar to if else
string result = (a > b) ? "a" : "b";
Console.WriteLine(result + " is greater");
}
}
Output
a is greater
Null Coalescing Operator 零合并
null-coalescing operator is used when we want to put a default value if the value of the variable is null.
Example:
using System;
public class Geeks
{
static public void Main()
{
string name = null;
// Name have null value takes default value instead of null
string result = name ? ? "Default Name";
Console.WriteLine(result);
}
}
Output
Default Name
Operator Associativity 运算符结合性
The following table summarizes the associativity of various operators in C#:
| Operator Type | Operators | Associativity |
|---|---|---|
| Postfix Operators | ++, – | Left to Right |
| Unary Operators | + , - , ! , ! | Right to Left |
| Multiplicative Operators | * , / , % | Left to Right |
| Additive Operators | + , - | Left to Right |
| Shift Operators | << , >> | Left to Right |
| Relational Operators | < , > , <= , >= | Left to Right |
| Equality Operators | ==, != | Left to Right |
| Bitwise operator | & , | , ^ | Left to Right |
| Logical Operator | && , || | Left to Right |
| Conditional Operator | " ? " | Right to Left |
| Assignment Operators | =, +=, -=, *=, /=, %=, … | Right to Left |
Explanation of Associativity
- Left to Right: For operators with left-to-right associativity, expressions are evaluated from the leftmost operator to the rightmost. For example, like a - b + c here the subtraction occurs before the addition.
- Right to Left: For operators with right-to-left associativity, such as assignment operators, expressions are evaluated from the rightmost operator to the leftmost. For example, a = b = c here c is assigned to b first then a.
Operator Precedence
Operator precedence is the most important to evaluate any expression because it gives us an idea about how the different operation performs and which one has the higher precedence.
The below table shows the precedence of different operators in C# in ascending order.
| Operator | Description |
|---|---|
| (), [], . | Parentheses, Array indexing, Member access |
| ++, --, !, ~ | Unary increment/decrement, logical NOT, bitwise NO.T |
| *, /, % | Multiplication, Division, Modulus |
| +, - | Addition, Subtraction |
| ==, !=, >, < | Relational operators |
Example:
// Operator Precedence
using System;
class Geeks
{
static void Main()
{
int a = 2, b = 4, c = 8;
// Multiplication precedence is higher so it performed first
int ans = a + b * c;
Console.WriteLine("Ans of a + b * c: " + ans);
// Addition has higher precedence
if( a + b > c)
Console.WriteLine(a + b);
}
}
Output
Ans of a + b * c: 34
Best Practices
- Parentheses: when there are multiple operations you can use () to specify which operation needs to be performed first like (a+b)*c here the operation inside the parentheses is performed first.
- Complex expressions: avoid using multiple operators together.
- Operator overloading: Sometimes It will create ambiguity in the program so make sure to define everything and use only what we need most.
1435

被折叠的 条评论
为什么被折叠?



