C# Tutoriallogin
C# Tutorial
author:php.cn  update time:2022-04-11 14:06:23

C# operators


C#Operator

An operator is a symbol that tells the compiler to perform a specific mathematical or logical operation. C# has a rich set of built-in operators, which are classified as follows:

  • Arithmetic operators

  • Relational operators

  • Logical operators

  • Bitwise operators

  • Assignment operators

  • Miscellaneous operations Operators

This tutorial will explain arithmetic operators, relational operators, logical operators, bitwise operators, assignment operators and other operators one by one.

Arithmetic operators

The following table shows all the arithmetic operators supported by C#. Assume that the value of variable A is 10 and the value of variable B is 20, then:

##Operator DescriptionExample+Add the two operandsA + B will get 30- Subtracting the second operand from the first operand A - B will give -10*Multiply the two operandsA * B will get 200/numerator Dividing by the denominator B / A will get 2%modulo operator, the remainder after integer divisionB % A will get 0++ auto-increment operator, the integer value is increased by 1A++ will get 11-- Decrement operator, reduce the integer value by 1A-- will get 9

Example

Look at the example below to learn about all the arithmetic operators available in C#:

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 21;
            int b = 10;
            int c;

            c = a + b;
            Console.WriteLine("Line 1 - c 的值是 {0}", c);
            c = a - b;
            Console.WriteLine("Line 2 - c 的值是 {0}", c);
            c = a * b;
            Console.WriteLine("Line 3 - c 的值是 {0}", c);
            c = a / b;
            Console.WriteLine("Line 4 - c 的值是 {0}", c);
            c = a % b;
            Console.WriteLine("Line 5 - c 的值是 {0}", c);

            // ++a 先进行自增运算再赋值
            c = ++a;
            Console.WriteLine("Line 6 - c 的值是 {0}", c);

            // 此时 a 的值为 22
            // --a 先进行自减运算再赋值
            c = --a;
            Console.WriteLine("Line 7 - c 的值是 {0}", c);
            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Line 1 - c 的值是 31
Line 2 - c 的值是 11
Line 3 - c 的值是 210
Line 4 - c 的值是 2
Line 5 - c 的值是 1
Line 6 - c 的值是 22
Line 7 - c 的值是 21
  • c = a++: First assign a to c, and then perform an increment operation on a.

  • c = ++a: First perform an increment operation on a, and then assign a to c.

  • c = a--: First assign a to c, and then perform a self-decrement operation on a.

  • c = --a: First perform a decrement operation on a, and then assign a to c.

Instance

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 1;
            int b;

            // a++ 先赋值再进行自增运算
            b = a++;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();

            // ++a 先进行自增运算再赋值
            a = 1; // 重新初始化 a
            b = ++a;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();

            // a-- 先赋值再进行自减运算
            a = 1;  // 重新初始化 a
            b= a--;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();

            // --a 先进行自减运算再赋值
            a = 1;  // 重新初始化 a
            b= --a;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();
        }
    }
}

Run Instance»

Click the "Run Instance" button View online examples


执行以上程序,输出结果为:
a = 2
b = 1
a = 2
b = 2
a = 0
b = 1
a = 0
b = 0

Relational operators

The following table shows all the relational operators supported by C#. Assume that the value of variable A is 10 and the value of variable B is 20, then:

##Operator DescriptionExample==Checks whether the values ​​of the two operands are equal. If they are equal, the condition is true. (A == B) is not true. != Checks whether the values ​​of the two operands are equal. If they are not equal, the condition is true. (A != B) is true. >Checks whether the value of the left operand is greater than the value of the right operand, if so, the condition is true. (A > B) is not true. <Checks whether the value of the left operand is less than the value of the right operand, if so the condition is true. (A < B) is true. >=Checks whether the value of the left operand is greater than or equal to the value of the right operand, if so the condition is true. (A >= B) is not true. <=Checks whether the value of the left operand is less than or equal to the value of the right operand, if so the condition is true. (A <= B) is true.

Example

See the example below to learn about all the relational operators available in C#:

using System;

class Program
{
  static void Main(string[] args)
  {
      int a = 21;
      int b = 10;
      
      if (a == b)
      {
          Console.WriteLine("Line 1 - a 等于 b");
      }
      else
      {
          Console.WriteLine("Line 1 - a 不等于 b");
      }
      if (a < b)
      {
          Console.WriteLine("Line 2 - a 小于 b");
      }
      else
      {
          Console.WriteLine("Line 2 - a 不小于 b");
      }
      if (a > b)
      {
          Console.WriteLine("Line 3 - a 大于 b");
      }
      else
      {
          Console.WriteLine("Line 3 - a 不大于 b");
      }
      /* 改变 a 和 b 的值 */
      a = 5;
      b = 20;
      if (a <= b)
      {
         Console.WriteLine("Line 4 - a 小于或等于 b");
      }
      if (b >= a)
      {
         Console.WriteLine("Line 5 - b 大于或等于 a");
      }
  }
}

When the above code is compiled and executed, it will produce the following results:

Line 1 - a 不等于 b
Line 2 - a 不小于 b
Line 3 - a 大于 b
Line 4 - a 小于或等于 b
Line 5 - b 大于或等于 a

Logical operators

The following table shows all the logical operators supported by C#. Assume that variable A is a Boolean value true and variable B is a Boolean value false, then:

##Operator DescriptionInstance&& is called the logical AND operator. The condition is true if both operands are non-zero. (A && B) is false. || is called the logical OR operator. The condition is true if either of the two operands is non-zero. (A || B) is true. ! is called the logical NOT operator. Used to reverse the logical state of the operand. The logical NOT operator will make the condition false if it is true. !(A && B) is true.
Example

Please look at the following example to understand all the logical operators available in C#:

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            bool a = true;
            bool b = true;
           
            if (a && b)
            {
               Console.WriteLine("Line 1 - 条件为真");
            }
            if (a || b)
            {
                Console.WriteLine("Line 2 - 条件为真");
            }
            /* 改变 a 和 b 的值 */
            a = false;
            b = true;
            if (a && b)
            {
                Console.WriteLine("Line 3 - 条件为真");
            }
            else
            {
                Console.WriteLine("Line 3 - 条件不为真");
            }
            if (!(a && b))
            {
                Console.WriteLine("Line 4 - 条件为真");
            }
            Console.ReadLine();
        }
    }
}

When the above code is When compiled and executed, it produces the following results:

Line 1 - 条件为真
Line 2 - 条件为真
Line 3 - 条件不为真
Line 4 - 条件为真

Bitwise Operators

Bitwise operators act on bits and perform operations bit by bit. The truth table for &, | and ^ is as follows:

pqp & qp | qp ^ q00000010111111010011

Suppose if A = 60, and B = 13, now expressed in binary format, they look like this:

A = 0011 1100

B = 0000 1101

-----------------

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The following table lists the bitwise operators supported by C#. Assume that the value of variable A is 60 and the value of variable B is 13, then:

##Operator DescriptionExample&The binary AND operator copies one bit to the result if both operands are present at the same time. (A & B) will get 12, which is 0000 1100|If present in any operand, binary OR operation character is copied into the result. (A | B) will get 61, which is 0011 1101^ if present in one of the operands but not both The binary XOR operator copies one of the two operands into the result. (A ^ B) will get 49, which is 0011 0001~The two's complement operator is a unary operator with " Flip" bit effect. (~A ) will get -61, which is 1100 0011, 2's complement, signed binary number. <<Binary left shift operator. The value of the left operand is shifted left by the number of bits specified by the right operand. A << 2 will get 240, which is 1111 0000##>>

Example

Look at the example below to see all the bitwise operators available in C#:

using System;
namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 60;	           /* 60 = 0011 1100 */  
            int b = 13;	           /* 13 = 0000 1101 */
            int c = 0;           

             c = a & b;           /* 12 = 0000 1100 */ 
             Console.WriteLine("Line 1 - c 的值是 {0}", c );

             c = a | b;           /* 61 = 0011 1101 */
             Console.WriteLine("Line 2 - c 的值是 {0}", c);

             c = a ^ b;           /* 49 = 0011 0001 */
             Console.WriteLine("Line 3 - c 的值是 {0}", c);

             c = ~a;               /*-61 = 1100 0011 */
             Console.WriteLine("Line 4 - c 的值是 {0}", c);

             c = a << 2;     /* 240 = 1111 0000 */
             Console.WriteLine("Line 5 - c 的值是 {0}", c);

             c = a >> 2;     /* 15 = 0000 1111 */
             Console.WriteLine("Line 6 - c 的值是 {0}", c);
            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it produces the following results:

Line 1 - c 的值是 12
Line 2 - c 的值是 61
Line 3 - c 的值是 49
Line 4 - c 的值是 -61
Line 5 - c 的值是 240
Line 6 - c 的值是 15

Assignment Operators

The following table lists the assignment operators supported by C#:

Binary right shift operator. The value of the left operand is shifted to the right by the number of bits specified by the right operand. A >> 2 will get 15, which is 0000 1111
##<<=left shift and assignment operatorC <<= 2 is equivalent to C = C < < 2>>=Right shift and assignment operatorC >>= 2 is equivalent to C = C >> 2##&=^=|=

Example

See the example below to learn about all the assignment operators available in C#:

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            int a = 21;
            int c;

            c = a;
            Console.WriteLine("Line 1 - =  c 的值 = {0}", c);

            c += a;
            Console.WriteLine("Line 2 - += c 的值 = {0}", c);

            c -= a;
            Console.WriteLine("Line 3 - -=  c 的值 = {0}", c);

            c *= a;
            Console.WriteLine("Line 4 - *=  c 的值 = {0}", c);

            c /= a;
            Console.WriteLine("Line 5 - /=  c 的值 = {0}", c);

            c = 200;
            c %= a;
            Console.WriteLine("Line 6 - %=  c 的值 = {0}", c);

            c <<= 2;
            Console.WriteLine("Line 7 - <<=  c 的值 = {0}", c);

            c >>= 2;
            Console.WriteLine("Line 8 - >>=  c 的值 = {0}", c);

            c &= 2;
            Console.WriteLine("Line 9 - &=  c 的值 = {0}", c);

            c ^= 2;
            Console.WriteLine("Line 10 - ^=  c 的值 = {0}", c);

            c |= 2;
            Console.WriteLine("Line 11 - |=  c 的值 = {0}", c);
            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it will produce the following results:

Line 1 - =     c 的值 = 21
Line 2 - +=    c 的值 = 42
Line 3 - -=    c 的值 = 21
Line 4 - *=    c 的值 = 441
Line 5 - /=    c 的值 = 21
Line 6 - %=    c 的值 = 11
Line 7 - <<=    c 的值 = 44
Line 8 - >>=    c 的值 = 11
Line 9 - &=    c 的值 = 2
Line 10 - ^=    c 的值 = 0
Line 11 - |=    c 的值 = 2

Miscellaneous operators

The following table lists some other important operators supported by C#, including sizeof, typeof and ?:.

Operator description example sizeof() returns the size of the data type. sizeof(int), will return 4. typeof() returns the type of class. typeof(StreamReader); & returns the address of the variable. &a; will get the actual address of the variable. *Pointer to variable. *a; will point to a variable. ?: conditional expression if the condition is true ? then X: otherwise Y is determines whether the object is of a certain type. If( Ford is Car) // Check whether Ford is an object of Car class. as cast, no exception will be thrown even if the conversion fails. Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;

Example

using System;

namespace OperatorsAppl
{
    
   class Program
   {
      static void Main(string[] args)
      {
         
         /* sizeof 运算符的实例 */
         Console.WriteLine("int 的大小是 {0}", sizeof(int));
         Console.WriteLine("short 的大小是 {0}", sizeof(short));
         Console.WriteLine("double 的大小是 {0}", sizeof(double));
         
         /* 三元运算符符的实例 */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("b 的值是 {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("b 的值是 {0}", b);
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it will produce the following results:

int 的大小是 4
short 的大小是 2
double 的大小是 8
b 的值是 30
b 的值是 20

Operator precedence in C

#The precedence of an operator determines the combination of terms in an expression. This affects how an expression is evaluated. Some operators have higher precedence than others, for example, multiplication and division operators have higher precedence than addition and subtraction operators.

For example x = 7 + 3 * 2, here, x is assigned the value 13 instead of 20, because the operator * has a higher priority than +, so the multiplication 3*2 is calculated first, and then Plus 7 more.

The following table lists each operator according to operator priority from high to low. Operators with higher priority appear at the top of the table, and operators with lower priority appear at the bottom of the table. under. In an expression, operators with higher precedence are evaluated first.

Operators DescriptionExample
=Simple assignment operator, assigns the value of the right operand to the left operand C = A + B will assign the value of A + B to the C
+= addition and assignment operator, adding the right operand to the left operand The result is assigned to the left operand C += A, which is equivalent to C = C + A
-=subtraction and assignment operator. The result of subtracting the right operand from the operand is assigned to the left operand C -= A which is equivalent to C = C - A
*= The multiplication and assignment operator assigns the result of multiplying the right operand by the left operand to the left operand C *= A which is equivalent to C = C * A
/=The division and assignment operator assigns the result of dividing the left operand by the right operand to the left operandC /= A is equivalent to C = C / A
%= Modulo and assignment operator, find the modulus of two operands and assign the value to the left operand C %= A is equivalent to C = C % A
Bitwise AND and assignment operatorC &= 2 is equivalent to C = C & 2
Bitwise XOR and assignment operatorC ^= 2 is equivalent to C = C ^ 2
Bitwise OR and assignment operatorC |= 2 is equivalent to C = C | 2
## bit OR | From left to right Logical AND && From left to right Logical OR || From left to right Condition ?: From right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= right to left ##comma Example
Category Operator Associativity
Suffix () [] -> . ++ - - From left to right
One yuan + - ! ~ ++ - - (type) * & sizeof From right to left
Multiplication and division * / % From left to right
Addition and subtraction + - From left to right
Shift << ; >> From left to right
Relationship < <= > >= From left to right
Equal == != From left to right
bits AND & from left to right
bit XOR XOR ^ from left To the right
, From left to right
using System;

namespace OperatorsAppl
{
    
   class Program
   {
      static void Main(string[] args)
      {
         int a = 20;
         int b = 10;
         int c = 15;
         int d = 5;
         int e;
         e = (a + b) * c / d;     // ( 30 * 15 ) / 5
         Console.WriteLine("(a + b) * c / d 的值是 {0}", e);

         e = ((a + b) * c) / d;   // (30 * 15 ) / 5
         Console.WriteLine("((a + b) * c) / d 的值是 {0}", e);

         e = (a + b) * (c / d);   // (30) * (15/5)
         Console.WriteLine("(a + b) * (c / d) 的值是 {0}", e);

         e = a + (b * c) / d;    //  20 + (150/5)
         Console.WriteLine("a + (b * c) / d 的值是 {0}", e);
         Console.ReadLine();
      }
   }
}

When the above code is compiled and executed, it will produce the following results:

(a + b) * c / d 的值是 90
((a + b) * c) / d 的值是 90
(a + b) * (c / d) 的值是 90
a + (b * c) / d 的值是 50