C#中的运算符

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:

  1. Arithmetic Operators 算术运算符
  2. Relational Operators 关系运算符
  3. Logical Operators 逻辑运算符
  4. Assignment Operators 赋值运算符
  5. Increment and Decrement Operators 递增和递减运算符
  6. Bitwise Operators 位运算符
  7. Ternary Operator 三元运算符
  8. Null Coalescing Operator 零合并算子

Arithmetic Operators 算术运算符

Arithmetic operators are used to perform basic mathematical operations on numeric values.

  1. Addition ( + ) 加号(+)
  2. Subtraction ( - ) 减法(-)
  3. Multiplication ( * ) 乘法(*)
  4. Division ( / ) 分配 ( / )
  5. 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 TypeOperatorsAssociativity
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.

OperatorDescription
(), [], .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.

文章引用地址

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值