Part 3: C# Fundamentals: Operators and Expressions

Image description

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.

OperatorDescriptionExampleResult
+Addition10 + 313
-Subtraction10 - 55
*Multiplication6 * 318
/Division8 / 24
%Modulus (remainder)10 % 31

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.");
}

2. Relational Operators

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

OperatorDescriptionExampleResult
==Equal to7 == 7true
!=Not equal to5 != 2true
<Less than4 < 8true
>Greater than9 > 7true
<=Less than or equal5 <= 5true
>=Greater or equal8 >= 12false

3. Logical Operators

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

OperatorDescriptionExampleResult
&&Logical ANDtrue && falsefalse
IILogical ORtrue II falsetrue
!Logical NOT!truefalse

Example:

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

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;

Example:

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

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

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}");
    }
}
TipsWeb DevelopmentDotnetBeginnersCsharp
Avatar for Adrián Bailador

Written by Adrián Bailador

🚀 Full-Stack Dev 👨🏻‍💻 .NET Engineer 👾 Geek & Friki 💡 Talks about #dotnet, #csharp, #azure, #visualstudio and a little bit of #nextjs.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.