DEV Community

Cover image for Part 3: C# Fundamentals: Operators and Expressions
Adrián Bailador
Adrián Bailador

Posted on

Part 3: C# Fundamentals: Operators and Expressions

In this lesson, we’ll explore operators and expressions in C#. These are fundamental concepts that allow you to perform calculations, make decisions, and create logic in your programs.

Operators are symbols used to perform operations, while expressions combine operators and values to produce results. Let’s dive in!

Types of Operators

C# provides a wide range of operators, categorized by their purpose.

1. Arithmetic Operators

These operators are used to perform basic mathematical calculations.

Operator Description Example Result
+ Addition 10 + 3 13
- Subtraction 10 - 5 5
* Multiplication 6 * 3 18
/ Division 8 / 2 4
% Modulus (remainder) 10 % 3 1

Important Note: Division by Zero

If you attempt to divide a number by zero, you’ll encounter an error or a special value like Infinity. Always check the divisor before performing the division.

int numerator = 10, divisor = 0;

if (divisor != 0)
{
    Console.WriteLine(numerator / divisor);
}
else
{
    Console.WriteLine("Error: Division by 0.");
}
Enter fullscreen mode Exit fullscreen mode

2. Relational Operators

These operators are used to compare values. The result of a comparison is either true or false.

Operator Description Example Result
== Equal to 7 == 7 true
!= Not equal to 5 != 2 true
< Less than 4 < 8 true
> Greater than 9 > 7 true
<= Less than or equal 5 <= 5 true
>= Greater or equal 8 >= 12 false

3. Logical Operators

Logical operators allow you to combine boolean expressions (true/false) to make more complex decisions.

Operator Description Example Result
&& Logical AND true && false false
ll Logical OR true ll false true
! Logical NOT !true false

Example:

string day = "Saturday";
bool isWeekend = day == "Saturday" || day == "Sunday";
Console.WriteLine($"Is it the weekend? {isWeekend}"); // true
Enter fullscreen mode Exit fullscreen mode

4. Ternary Operator

The ternary operator is a compact and elegant way to make decisions in a single line of code.

The structure is:

condition ? valueIfTrue : valueIfFalse;
Enter fullscreen mode Exit fullscreen mode

Example:

int age = 18;
string message = age >= 18 ? "You are an adult" : "You are a minor";
Console.WriteLine(message); // Output: You are an adult
Enter fullscreen mode Exit fullscreen mode

Additional Example: Determine the Sign of a Number

int number = -5;
string state = number > 0 ? "positive" : (number < 0 ? "negative" : "zero");
Console.WriteLine($"The number {number} is {state}."); // negative
Enter fullscreen mode Exit fullscreen mode

Example: Basic Calculator

Let’s create a calculator that allows the user to perform basic arithmetic operations.

using System;

class BasicCalculator
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter the first number:");
        double number1 = Convert.ToDouble(Console.ReadLine());

        Console.WriteLine("Enter the operator (+, -, *, /):");
        char operatorChar = Console.ReadLine()[0];

        Console.WriteLine("Enter the second number:");
        double number2 = Convert.ToDouble(Console.ReadLine());

        double result = operatorChar switch
        {
            '+' => number1 + number2,
            '-' => number1 - number2,
            '*' => number1 * number2,
            '/' => number2 != 0 ? number1 / number2 : double.NaN,
            _ => double.NaN
        };

        Console.WriteLine($"The result is: {result}");
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)