C# Operators

An operator is a symbol that tells the compiler to perform specific mathematical or logical operations. C# has rich built-in operators, categorized as follows:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Other 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 arithmetic operators supported by C#. Assume variableAhas a value of 10, variableBhas a value of 20, then:

OperatorsDescriptionExample
+Adds two operands.A + B will result in 30
-Subtracts the second operand from the first operand.A - B will result in -10
*Multiplies two operands.A * B will result in 200
/Numerator divided by denominatorB / A will result in 2
%Modulus operator, remainder after integer division.B % A will result in 0
++Increment operator, increases an integer value by 1.A++ will result in 11
--Decrement operator, decreases an integer value by 1.A-- will result in 9

Example

See the example below to understand all the arithmetic operators available in C#:

Example

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 - the value of c is {0}", c);
            c = a - b;
            Console.WriteLine("Line 2 - the value of c is {0}", c);
            c = a * b;
            Console.WriteLine("Line 3 - the value of c is {0}", c);
            c = a / b;
            Console.WriteLine("Line 4 - the value of c is {0}", c);
            c = a % b;
            Console.WriteLine("Line 5 - the value of c is {0}", c);

            // ++a increments before assignment
            c = ++a;
            Console.WriteLine("Line 6 - the value of c is {0}", c);

            // At this point, the value of a is 22
            // --a decrements before assignment
            c = --a;
            Console.WriteLine(Line 7 - The value of c is {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++: Assign a to c first, then increment a.
  • c = ++a: Increment a first, then assign a to c.
  • c = a--: Assign a to c first, then decrement a.
  • c = --a: Decrement a first, then assign a to c.

Example

using System;

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

            // a++ assigns before incrementing
            b = a++;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();

            // ++a increments before assignment
            a = 1; // Reinitialize a
            b = ++a;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();

            // a-- assigns before decrementing
            a = 1;  // Reinitialize a
            b= a--;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();

            // --a decrements before assignment
            a = 1;  // Reinitialize a
            b= --a;
            Console.WriteLine("a = {0}", a);
            Console.WriteLine("b = {0}", b);
            Console.ReadLine();
        }
    }
}

Run Example »

Executing the above program, the output result is:

a = 2
b = 1
a = 2
b = 2
a = 0
b = 1
a = 0
b = 0

Relational Operators

The following table shows all relational operators supported by C#. Assume variableAhas a value of 10, variableBhas a value of 20, then:

OperatorsDescriptionExample
==Checks whether the values of two operands are equal; if they are equal, the condition is true.(A == B) is not true.
!=Checks whether the values of 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 understand all the relational operators available in C#:

Example

using System;

class Program
{
  static void Main(string[] args)
  {
      int a = 21;
      int b = 10;
     
      if (a == b)
      {
          Console.WriteLine("Line 1 - a equals b");
      }
      else
      {
          Console.WriteLine("Line 1 - a is not equal to b");
      }
      if (a < b)
      {
          Console.WriteLine("Line 2 - a is less than b");
      }
      else
      {
          Console.WriteLine("Line 2 - a is not less than b");
      }
      if (a > b)
      {
          Console.WriteLine("Line 3 - a is greater than b");
      }
      else
      {
          Console.WriteLine("Line 3 - a is not greater than b");
      }
      /* Change the values of a and b */
      a = 5;
      b = 20;
      if (a <= b)
      {
         Console.WriteLine(Line 4 - a is less than or equal to b);
      }
      if (b >= a)
      {
         Console.WriteLine(Line 5 - b is greater than or equal to a);
      }
  }
}

When the above code is compiled and executed, it produces 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 logical operators supported by C#. Assume variableAis a Boolean value true, variableBis a Boolean value false, then:

OperatorsDescriptionExample
&&Called the logical AND operator. If both operands are non-zero, the condition is true.(A && B) is false.
||Called the logical OR operator. If either operand is non-zero, the condition is true.(A || B) is true.
!Called the logical NOT operator. It is used to reverse the logical state of an operand. If the condition is true, the logical NOT operator will make it false.!(A && B) is true.

Example

See the example below to understand all the logical operators available in C#:

Example

using System;

namespace OperatorsAppl
{
    class Program
    {
        static void Main(string[] args)
        {
            bool a = true;
            bool b = true;
           
            if (a && b)
            {
               Console.WriteLine(Line 1 - condition is true);
            }
            if (a || b)
            {
                Console.WriteLine(Line 2 - condition is true);
            }
            /* Change the values of a and b */
            a = false;
            b = true;
            if (a && b)
            {
                Console.WriteLine(Line 3 - condition is true);
            }
            else
            {
                Console.WriteLine("Line 3 - condition is not true");
            }
            if (!(a && b))
            {
                Console.WriteLine(Line 4 - condition is true);
            }
            Console.ReadLine();
        }
    }
}

When the above code is 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 tables for &, |, and ^ are as follows:

pqp & qp | qp ^ q
00000
01011
11110
10011

Suppose A = 60 and B = 13. Now expressed in binary format, they are as follows:

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 variableAhas a value of 60, variableBhas a value of 13, then:

OperatorsDescriptionExample
&If present in both operands, the binary AND operator copies a bit to the result.(A & B) evaluates to 12, which is 0000 1100.
|If present in either operand, the binary OR operator copies a bit to the result.(A | B) evaluates to 61, which is 0011 1101.
^If present in one operand but not both, the binary XOR operator copies a bit to the result.(A ^ B) evaluates to 49, which is 0011 0001.
~The bitwise complement operator is a unary operator that has the effect of "flipping" bits, that is, 0 becomes 1 and 1 becomes 0, including the sign bit.(~A ) will result in -61, which is 1100 0011, the two's complement form of a 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 evaluates to 240, which is 1111 0000.
>>Binary right shift operator. The value of the left operand is shifted right by the number of bits specified by the right operand.A >> 2 evaluates to 15, which is 0000 1111.

Example

See the example below to understand all the bitwise operators available in C#:

Example

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 - the value of c is {0}", c );

             c = a | b;           /* 61 = 0011 1101 */
             Console.WriteLine("Line 2 - the value of c is {0}", c);

             c = a ^ b;           /* 49 = 0011 0001 */
             Console.WriteLine("Line 3 - the value of c is {0}", c);

             c = ~a;               /*-61 = 1100 0011 */
             Console.WriteLine("Line 4 - the value of c is {0}", c);

             c = a << 2;     /* 240 = 1111 0000 */
             Console.WriteLine("Line 5 - the value of c is {0}", c);

             c = a >> 2;     /* 15 = 0000 1111 */
             Console.WriteLine("Line 6 - the value of c is {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#:

OperatorsDescriptionExample
=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 C
+=Add and assignment operator, assigns to the left operand the result of adding the right operand to the left operand.C += A is equivalent to C = C + A.
-=Subtract and assignment operator, assigns to the left operand the result of subtracting the right operand from the left operand.C -= A is equivalent to C = C - A.
*=Multiply and assignment operator, assigns to the left operand the result of multiplying the right operand by the left operand.C *= A is equivalent to C = C * A.
/=Divide and assignment operator, assigns to the left operand the result of dividing the left operand by the right operand.C /= A is equivalent to C = C / A.
%=Modulus and assignment operator, takes the modulus of two operands and assigns it to the left operand.C %= A is equivalent to C = C % A.
<<=Left shift and assignment operator.C <<= 2 is equivalent to C = C << 2
>>=Right shift and assignment operator.C >>= 2 is equivalent to C = C >> 2
&=Bitwise AND and assignment operator.C &= 2 is equivalent to C = C & 2
^=Bitwise XOR and assignment operator.C ^= 2 is equivalent to C = C ^ 2
|=Bitwise OR and assignment operator.C |= 2 is equivalent to C = C | 2

Example

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

Example

using System;

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

            c = a;
            Console.WriteLine(Line 1 - = value of c = {0}, c);

            c += a;
            Console.WriteLine(Line 2 - += value of c = {0}, c);

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

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

            c /= a;
            Console.WriteLine(Line 5 - /= value of c = {0}, c);

            c = 200;
            c %= a;
            Console.WriteLine(Line 6 - %= value of c = {0}, c);

            c <<= 2;
            Console.WriteLine(Line 7 - <<= c's value = {0}, c);

            c >>= 2;
            Console.WriteLine(Line 8 - >>= c's value = {0}, c);

            c &= 2;
            Console.WriteLine(Line 9 - &= value of c = {0}, c);

            c ^= 2;
            Console.WriteLine(Line 10 - ^= c's value = {0}, c);

            c |= 2;
            Console.WriteLine(Line 11 - |= c's value = {0}, c);
            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it produces 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

Other Operators

The following table lists some other important operators supported by C#, includingsizeof、typeofand? :。

OperatorsDescriptionExample
sizeof()Returns the size of a data type.sizeof(int) will return 4.
typeof()Returns the type of a class.typeof(StreamReader);
&Returns the address of a variable.&a; will get the actual address of the variable.
*Pointer to a variable.*a; points to a variable.
? :Conditional expressionIf the condition is true ? then X : otherwise Y
isDetermines whether an object is of a certain type.If( Ford is Car) // Check whether Ford is an object of the Car class.
asCast conversion, even if the conversion fails, it will not throw an exception.Object obj = new StringReader("Hello");
StringReader r = obj as StringReader;

Example

Example

using System;

namespace OperatorsAppl
{
   
   class Program
   {
      static void Main(string[] args)
      {
         
         /* Example of the sizeof operator */
         Console.WriteLine("The size of int is {0}", sizeof(int));
         Console.WriteLine("The size of short is {0}", sizeof(short));
         Console.WriteLine("The size of double is {0}", sizeof(double));
         
         /* Example of the ternary operator */
         int a, b;
         a = 10;
         b = (a == 1) ? 20 : 30;
         Console.WriteLine("The value of b is {0}", b);

         b = (a == 10) ? 20 : 30;
         Console.WriteLine("The value of b is {0}", b);
         Console.ReadLine();
      }
   }
}

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

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

The typeof keyword is used to obtain the type object of a type; it is commonly used for reflection and dynamically creating type instances.

Here is a simple example using typeof:

Example

using System;

class Program
{
    static void Main(string[] args)
    {
        Type type = typeof(string);
        Console.WriteLine(type.FullName);
        Console.ReadKey();
    }
}

In the above code, we use the typeof keyword to obtain the type object of the string type and store it in a variable type of type Type. Then, we use the FullName property to print the fully qualified name of that type.

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

System.String

Operator precedence in C#

Operator precedence determines the grouping 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 13, not 20, because the operator * has higher precedence than +, so the multiplication 3*2 is calculated first, and then 7 is added.

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

A simple overview of precedence.: Parentheses first, then multiplication/division, then addition/subtraction, then shifts, then relational, then logical, then conditional, and finally comma., 。

Category OperatorsAssociativity
Postfix() [] -> . ++ - -   Left to right
Unary + - ! ~ ++ - - (type)* & sizeof  Right to left
Multiplicative * / % Left to right
Additive+ -  Left to right
Shift << >>  Left to right
Relationship< <= > >=  Left to right
Equality == !=  Left to right
Bitwise AND&  Left to right
Bitwise XOR ^  Left to right
Bitwise OR |  Left to right
Logical AND&&  Left to right
Logical OR ||  Left to right
Conditions?:  Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left
comma ,  Left to right

Example

Example

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(The value of (a + b) * c / d is {0}, e);

         e = ((a + b) * c) / d;   // (30 * 15 ) / 5
         Console.WriteLine("The value of ((a + b) * c) / d is {0}", e);

         e = (a + b) * (c / d);   // (30) * (15/5)
         Console.WriteLine("The value of (a + b) * (c / d) is {0}", e);

         e = a + (b * c) / d;    //  20 + (150/5)
         Console.WriteLine(The value of a + (b * c) / d is {0}, e);
         Console.ReadLine();
      }
   }
}

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

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

Precedence of arithmetic operators and assignment operators:

Example

int a = 10, b = 5, c = 2;
int result = a + b * c;  // First calculate multiplication, then addition
Console.WriteLine(result);  // output 20

result = (a + b) * c;     // First calculate addition, then multiplication
Console.WriteLine(result);  // output 30

a += b * c;               // Calculate multiplication first, then perform the addition assignment
Console.WriteLine(a);       // output 20

Precedence of logical operators:

Example


bool a = true, b = false, c = true;
bool result = a || b && c;  // Compute the AND operation first, then the OR operation
Console.WriteLine(result);  // Output true

result = (a || b) && c;     // Compute the OR operation first, then the AND operation
Console.WriteLine(result);  // Output true

result = a || (b && c);     // Compute the AND operation first, then the OR operation
Console.WriteLine(result);  // Output true

Precedence of conditional operators:

Example

int a = 10, b = 5;
string result = a > b ? "a is greater than b" : "a is not greater than b";  // First determine the size relationship, then execute the conditional statement
Console.WriteLine(result);  // Output "a is greater than b"

Note:Since parentheses can change operator precedence, in practical applications it is recommended to use parentheses as much as possible to clarify the order of operations and improve code readability and accuracy.

other extensions