404 Not Found

404 Not Found


nginx

Operators and Expressions

Arithmetic Operators

Arithmetic operators perform basic math operations including addition, subtraction, multiplication, division, and modulus.

Operator Name Example Result
+ Addition 5 + 3 8
- Subtraction 5 - 3 2
* Multiplication 5 * 3 15
/ Division 7 / 2 3
% Modulus 7 % 2 1

Warning: Integer division truncates the decimal part. 7 / 2 yields 3, not 3.5. To get a floating-point result, at least one operand must be a floating-point type, e.g., 7.0 / 2 yields 3.5.

Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        int a = 17, b = 5;

        Console.WriteLine($"Addition: {a} + {b} = {a + b}");
        Console.WriteLine($"Subtraction: {a} - {b} = {a - b}");
        Console.WriteLine($"Multiplication: {a} * {b} = {a * b}");
        Console.WriteLine($"Integer division: {a} / {b} = {a / b}");
        Console.WriteLine($"Floating-point division: {a * 1.0} / {b} = {a * 1.0 / b}");
        Console.WriteLine($"Modulus: {a} % {b} = {a % b}");
    }
}
▶ Try it Yourself
TEXT
Addition: 17 + 5 = 22
Subtraction: 17 - 5 = 12
Multiplication: 17 * 5 = 85
Integer division: 17 / 5 = 3
Floating-point division: 17 / 5 = 3.4
Modulus: 17 % 5 = 2

Increment and Decrement Operators

The increment ++ and decrement -- operators increase or decrease a variable's value by 1. The prefix form modifies the value before use; the postfix form uses the value first, then modifies it.

Operator Name Description
++x Prefix increment Increment by 1, then use the value
x++ Postfix increment Use the value, then increment by 1
--x Prefix decrement Decrement by 1, then use the value
x-- Postfix decrement Use the value, then decrement by 1

Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        int x = 10;
        int y = 10;

        Console.WriteLine($"Prefix increment: ++x = {++x}, x = {x}");
        Console.WriteLine($"Postfix increment: y++ = {y++}, y = {y}");

        int m = 5;
        int n = 5;

        Console.WriteLine($"Prefix decrement: --m = {--m}, m = {m}");
        Console.WriteLine($"Postfix decrement: n-- = {n--}, n = {n}");
    }
}
▶ Try it Yourself
TEXT
Prefix increment: ++x = 11, x = 11
Postfix increment: y++ = 10, y = 11
Prefix decrement: --m = 4, m = 4
Postfix decrement: n-- = 5, n = 4

Relational Operators

Relational operators compare two values and return a bool result (true or false).

Operator Name Example Result
== Equal to 5 == 5 true
!= Not equal to 5 != 3 true
< Less than 3 < 5 true
> Greater than 5 > 3 true
<= Less than or equal 5 <= 5 true
>= Greater than or equal 5 >= 6 false

Tip: Do not confuse = (assignment) with == (equality check). Using = in an if condition causes a compile error or logic bug.

Logical Operators

Logical operators combine boolean expressions. C# uses && and || with short-circuit evaluation, meaning the second operand is not evaluated when the result is already determined.

Operator Name Example Description
&& Logical AND a && b True if both are true (short-circuit)
` ` Logical OR
! Logical NOT !a Negates the value

Warning: Use && and || for logical operations in C#, not & and |. The latter are bitwise operators that can also operate on booleans but do not short-circuit.

Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        int age = 25;
        bool hasLicense = true;

        bool canDrive = age >= 18 && hasLicense;
        Console.WriteLine($"Can drive: {canDrive}");

        bool isWeekend = false;
        bool isHoliday = true;
        bool dayOff = isWeekend || isHoliday;
        Console.WriteLine($"Day off: {dayOff}");

        bool isRaining = true;
        Console.WriteLine($"Not raining: {!isRaining}");
    }
}
▶ Try it Yourself
TEXT
Can drive: True
Day off: True
Not raining: False

Assignment Operators

Assignment operators assign values to variables. Compound assignment operators combine an operation and assignment into one step.

Operator Equivalent Example
= x = 10
+= x = x + y x += 5
-= x = x - y x -= 3
*= x = x * y x *= 2
/= x = x / y x /= 4
%= x = x % y x %= 3

Conditional Operator

The conditional operator ?: is C#'s only ternary operator. It returns one of two values based on a condition.

Syntax: condition ? valueIfTrue : valueIfFalse

Example

CSHARP
using System;

class Program
{
    static void Main()
    {
        int score = 72;
        string result = score >= 60 ? "Pass" : "Fail";
        Console.WriteLine($"Score {score}: {result}");

        int a = 15, b = 9;
        int max = a > b ? a : b;
        Console.WriteLine($"Larger value: {max}");
    }
}
▶ Try it Yourself
TEXT
Score 72: Pass
Larger value: 15

Null-Coalescing Operator

The ?? operator returns the right-hand operand when the left-hand operand is null; otherwise, it returns the left-hand value. The ??= operator (C# 8) is the null-coalescing assignment operator that assigns a value only when the variable is null.

CSHARP
using System;

class Program
{
    static void Main()
    {
        string name = null;
        string display = name ?? "Anonymous";
        Console.WriteLine($"Name: {display}");

        int? count = null;
        int total = count ?? 0;
        Console.WriteLine($"Total: {total}");

        string title = null;
        title ??= "Default Title";
        Console.WriteLine($"Title: {title}");

        title ??= "New Title";
        Console.WriteLine($"Title: {title}");
    }
}
TEXT
Name: Anonymous
Total: 0
Title: Default Title
Title: Default Title

Null-Conditional Operator

The ?. operator checks whether an object is null before accessing a member. If the object is null, the expression returns null instead of throwing a NullReferenceException.

CSHARP
using System;

class Program
{
    static void Main()
    {
        string text = "Hello C#";
        Console.WriteLine($"Length: {text?.Length}");

        text = null;
        Console.WriteLine($"Length: {text?.Length}");

        int? len = text?.Length;
        Console.WriteLine($"Type: {len?.GetType().Name ?? "null"}");
    }
}
TEXT
Length: 8
Length:
Type: null

Operator Precedence

The table below lists common C# operators from highest to lowest precedence. Operators on the same row have equal precedence.

Priority Operators Description
1 x++ x-- . ?. () [] Postfix, member access
2 ++x --x +x -x ! ~ Prefix, unary
3 * / % Multiplicative
4 + - Additive
5 < > <= >= is as Relational, type check
6 == != Equality
7 && Logical AND
8 `
9 ?? ??= Null-coalescing
10 ?: Conditional
11 = += -= *= /= %= etc. Assignment

Tip: When in doubt about precedence, use parentheses () to make the evaluation order explicit. This prevents errors and improves readability.

❓ FAQ

Q What is the difference between integer division and floating-point division?
A Integer division truncates the decimal part, e.g., 7 / 2 yields 3; floating-point division preserves decimals, e.g., 7.0 / 2 yields 3.5.
Q What is the difference between ++x and x++?
A ++x increments first and returns the new value; x++ returns the current value then increments. In a standalone statement they behave the same, but within an expression the results differ.
Q What is the difference between && and &?
A && is a short-circuit logical AND that skips the right operand when the left is false; & is a bitwise AND that can also operate on booleans but always evaluates both sides.
Q When should I use ?? vs ?.?
A Use ?? to provide a default value when null; use ?. to safely access a member on a potentially null object, avoiding NullReferenceException.

📖 Summary

📝 Exercises

  1. Write a program that computes 7 / 2 and 7.0 / 2 and outputs the results, verifying the truncation behavior of integer division.
  2. Write a program demonstrating the difference between ++x and x++ in an expression: set int a = 5, then compute ++a * 3 and a++ * 3 separately and output the results.
  3. Write a program that uses the conditional operator to determine whether an integer is positive, zero, or negative (nesting ?: is allowed).
  4. Write a program that creates a string variable set to null, then uses ?? and ?. to output its default value and safely access its length.
  5. Write a program that evaluates 2 + 3 * 4 and (2 + 3) * 4, demonstrating how parentheses affect precedence.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏