C# (.NET 8 LTS) track

Lesson 03 · Part 1: Basics

Operators and Expressions

Use C# operators to calculate values, compare results and handle nulls safely.

Part 1: Basics5 min readFree lesson

Operators are basic tools for manipulating values. In addition to the common Arithmetic/Comparison/Logic, C# is rich in expression-friendly features such as the null safe operator, pattern matching (is), and ternary operator (?:).

Learning Objectives

  • Know the priority of the Arithmetic/Comparison/Logic operator.
  • Understand the difference in results between int / int and double / int
  • Know the short-circuit operation of && / ||
  • Handle null safely with ?. ?? ??=
  • Type check and conversion with is / as
  • Write expressions concisely with the ternary operator ?:

Key concepts

1) Arithmetic operators

There are +, -, *, /, and %. The key is type rules.

int x = 7 / 2;        //3 (integer division, decimal point truncated)
double y = 7 / 2;     //3.0 (first integer division and then double conversion)
double z = 7.0 / 2;   //3.5 (if one side is double, real number division)
int r = 7 % 2;        //1 (remainder)

2) Comparison and logical operators

  • Comparison: ==, !=, <, <=, >, >= → bool returns
  • Logic: &&(AND), ||(OR), !(NOT)

Short-circuit evaluation: && does not look to the right if false is to the left. || does not look to the right if true is to the left.

int? n = null;
if (n != null && n.Value > 0)   //If n == null, .Value is not evaluated.
    Console.WriteLine("positive number");

3) Null-conditional ?. and null-coalescing ??, ??=

  • obj?.Member: If obj is null, the entire evaluation is null, otherwise, Member is evaluated.
  • a ?? b: If a is null, then b
  • a ??= b: Substitute b only when a is null
string? name = null;
int len = name?.Length ?? 0;          //If null it is 0
name ??= "(no name)";               //Assign only when null
Console.WriteLine($"{name} ({len})"); //(no name) (0)

4) is and as

  • obj is Type: If the type is true, it can be combined with pattern matching.
  • obj as Type: When casting fails, null** instead of **exception
object o = "hello";
if (o is string s)                 //Type checking + variable declaration
    Console.WriteLine(s.Length);   // 5

object o2 = 42;
string? s2 = o2 as string;         //Casting failed → s2 == null

5) Ternary operator ?:

"condition ? true value : false value" — short if-else as an expression.

int score = 75;
string grade = score >= 60 ? "passed" : "failed";

See as example

Example 1 — Arithmetic/Program.cs: Integer vs real division

int a = 7, b = 2;

Console.WriteLine($"{a} + {b} = {a + b}");
Console.WriteLine($"{a} - {b} = {a - b}");
Console.WriteLine($"{a} * {b} = {a * b}");
Console.WriteLine($"{a} / {b} = {a / b} (integer division)");
Console.WriteLine($"{a} % {b} = {a % b}");
Console.WriteLine($"(double)a / b = {(double)a / b} (real division)");

Execution result

7 + 2 = 9
7 - 2 = 5
7 * 2 = 14
7 / 2 = 3 (integer division)
7 % 2 = 1
(double)a / b = 3.5 (real division)

Note: Even if you cast only one side as (double), the result will be double.

Example 2 — LogicalOps/Program.cs: Demonstrating short-circuit evaluation

static bool Log(string label, bool value)
{
    Console.WriteLine($"[{label} evaluated → {value}]");
    return value;
}

Console.WriteLine("(false &&");
bool r1 = Log("A", false) && Log("B", true);
Console.WriteLine($"  => {r1}");

Console.WriteLine("(true ||");
bool r2 = Log("C", true) || Log("D", false);
Console.WriteLine($"  => {r2}");

Execution result

(false &&
[A rated → False]
  => False
(true ||
[Rated C → True]
  => True

Note: B, D are not evaluated. This is a paragraph evaluation.

Example 3 — NullSafety/Program.cs : ?. ?? ??=

string? name = null;

int len = name?.Length ?? 0;          //If null it is 0
Console.WriteLine($"Length: {len}");

name ??= "(no name)";               //Assign only when null
Console.WriteLine($"Name: {name}");

//Once again: now it's not null so it doesn't change
name ??= "another default";
Console.WriteLine($"final: {name}");

Execution result

Length: 0
Name: (no name)
Final: (unnamed)

Memo: When ?. is null, the entire expression becomes null. So I often use it as a companion to ??.

Example 4 — IsAs/Program.cs: Type checking and casting

object[] items = ["hello", 42, 3.14, true];

foreach (object item in items)
{
    if (item is string s)
        Console.WriteLine($"String: '{s}' (length {s.Length})");
    else if (item is int n)
        Console.WriteLine($"integer: {n}");
    else
        Console.WriteLine($"Other: {item} ({item.GetType().Name})");
}

object boxed = 100;
string? wrong = boxed as string;      //Casting failed → null
Console.WriteLine($"as result: {wrong ??"(null)"}");

Execution result

String: 'hello' (length 5)
Integer: 42
Others: 3.14 (Double)
Other: True (Boolean)
as result: (null)

Note: The is Type variable pattern is the cleanest. If you force cast like (string)boxed, an exception will occur if it fails, so if you want to be safe, use as or is.

Common Mistakes

  1. Expect 7 / 2 to be 3.5 — Integer division between integers.
  2. Confusion between = and == like if (count = 0) — In C#, an expression other than bool cannot be inserted into if, so a compilation error occurs, so it is safe, but be careful.
  3. Confusion between ?? and ?: — ?? is null or not, and ?: is general condition.
  4. Cast value type as as — as int is not possible, must be written as as int?.
  5. Access the object null as . → NullReferenceException. Always consider ?..

Cleanup

  • Integer Division/Real-numbers distinguishes division
  • Safe null check and chain check with short circuit evaluation of &&/||
  • ?. ?? ??= is a set of 3 null processing
  • Safely check and convert types with is/as
  • Ternary ?: neatly expresses short branches

Try it yourself

cd src/Arithmetic && dotnet run
cd ../LogicalOps && dotnet run
cd ../NullSafety && dotnet run
cd ../IsAs && dotnet run

Example files

The runnable files used in this lesson. Copy them into your own project and experiment.

src/Arithmetic/Arithmetic.csprojText
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics03</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
src/Arithmetic/Program.csC#
//Arithmetic Operators - Integer vs. Real Division
int a = 7, b = 2;

Console.WriteLine($"{a} + {b} = {a + b}");
Console.WriteLine($"{a} - {b} = {a - b}");
Console.WriteLine($"{a} * {b} = {a * b}");
Console.WriteLine($"{a} / {b} = {a / b} (integer division)");
Console.WriteLine($"{a} % {b} = {a % b}");
Console.WriteLine($"(double)a / b = {(double)a / b} (real division)");
src/IsAs/IsAs.csprojText
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics03</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
src/IsAs/Program.csC#
//is / as type checking and casting
object[] items = ["hello", 42, 3.14, true];

foreach (object item in items)
{
    if (item is string s)
        Console.WriteLine($"String: '{s}' (length {s.Length})");
    else if (item is int n)
        Console.WriteLine($"integer: {n}");
    else
        Console.WriteLine($"Other: {item} ({item.GetType().Name})");
}

object boxed = 100;
string? wrong = boxed as string;      //Casting failed → null
Console.WriteLine($"as result: {wrong ??"(null)"}");
src/LogicalOps/LogicalOps.csprojText
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics03</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
src/LogicalOps/Program.csC#
//&& / || Demonstration of paragraph evaluation of
static bool Log(string label, bool value)
{
    Console.WriteLine($"[{label} evaluated → {value}]");
    return value;
}

Console.WriteLine("(false &&");
bool r1 = Log("A", false) && Log("B", true);
Console.WriteLine($"  => {r1}");

Console.WriteLine("(true ||");
bool r2 = Log("C", true) || Log("D", false);
Console.WriteLine($"  => {r2}");
src/NullSafety/NullSafety.csprojText
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics03</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
src/NullSafety/Program.csC#
//?. ?? ??= Demonstration
string? name = null;

int len = name?.Length ?? 0;          //If null it is 0
Console.WriteLine($"Length: {len}");

name ??= "(no name)";               //Assign only when null
Console.WriteLine($"Name: {name}");

//Since the value already exists, it will not change.
name ??= "another default";
Console.WriteLine($"final: {name}");

Assignment

Problem 1 — BMI Calculator

  • Reference solution: shown below
  • Core concepts: double operations, comparison operators, string interpolation :F2

Requirements

  • Enter your height (cm) and weight (kg)
  • Calculate BMI = Weight/Height-m-Height-m
  • Output to two decimal places ({bmi:F2})

Expected output

Height (cm): 172
Weight (kg): 70
BMI: 23.66

Hint

  • To change cm to m, / 100.0 (be sure to use 100.0 — double is guaranteed)
  • Enter real number as double.Parse(Console.ReadLine()!)

Problem 2 — Determining Even/odd (ternary operator)

  • Reference solution: shown below
  • Key concepts: %, ternary operator ?:

Requirements

  • Receives an integer as input
  • Determine and output even/odd-numbers using the ternary operator.
  • If 0 is entered, “0 is an even number” is output (0 is treated as an even number)

Expected output

Integer: 7
7 is an odd number.

Hint

  • If n % 2 == 0 is an even number
  • string result = ... ? "even" : "odd";

Check the correct answer

After solving it yourself, compare it with the reference solution below.

Show the reference solution

Try the assignment yourself first — comparing your attempt with a working solution is where most of the learning happens.

Homework01/Homework01.csprojText
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics03</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
Homework01/Program.csC#
//BMI calculator
Console.Write("Height (cm):");
double heightCm = double.Parse(Console.ReadLine()!);

Console.Write("Weight (kg):");
double weightKg = double.Parse(Console.ReadLine()!);

double heightM = heightCm / 100.0;
double bmi = weightKg / (heightM * heightM);

Console.WriteLine($"BMI: {bmi:F2}");
Homework02/Homework02.csprojText
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net8.0</TargetFramework>
    <RootNamespace>CodingNow.Lecture.Basics03</RootNamespace>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

</Project>
Homework02/Program.csC#
//Even/odd discrimination - ternary operator
Console.Write("Integer:");
int n = int.Parse(Console.ReadLine()!);

string kind = n % 2 == 0 ? "even number" : "odd number";
Console.WriteLine($"{n} is {kind}.");

Learn this lesson with a mentor

Work through the C# (.NET 8 LTS) track on your own, or join a guided cohort at our Pitampura campus and online.

Call NowEnroll Now