C# Foundations·C# from first file to first API

Variables and control flow

C# variables are typed, and branching and loops decide what runs next.

Beginner 12 min read Lesson 1 of 300 Challenge included
What you will be able to do
  • Prefer var when the type is obvious; be explicit when it adds clarity.
  • Use a switch expression for value selection and if/else for branching actions.
  • Declare variables in the smallest scope you can.

In plain English

A variable names a value the program can change, and its type tells the compiler what that value can do. var lets the compiler infer the type, while an explicit type like int documents your intent. if and else choose between two paths, and a switch expression picks one result from many cases. Loops such as for, foreach and while repeat code, and scope decides where a variable is visible.

Step by step

  1. 1Declare a string and an inferred var, then print both.
  2. 2Branch with if/else and add a switch expression.
  3. 3Repeat with for and foreach loops.
  4. 4Move a variable into a narrower scope and watch it go out of reach.
Program.csC#
string title = "C# Foundations";
var minutes = 12;

if (minutes > 10)
{
    Console.WriteLine(title + " is a long lesson");
}
else
{
    Console.WriteLine(title + " is a short lesson");
}

var label = minutes switch
{
    <= 10 => "short",
    <= 20 => "medium",
    _ => "long",
};
Console.WriteLine(label);

for (var i = 0; i < 3; i++)
{
    Console.Write(".");
}
Console.WriteLine();

foreach (var word in title.Split(' '))
{
    Console.WriteLine(word);
}

Common mistakes

  • Redeclaring the same variable name in the same scope causes a compile error.
  • Comparing strings with == instead of Equals can surprise you when case matters.
  • Putting a variable in a wide scope invites accidental reuse and bugs.
  • Off-by-one loop bounds either skip the last item or run once too many.
Your turn

Classify a lesson length

Easy

Write a switch expression that returns short, medium or long from a lesson minutes value: short when 10 or less, medium when 20 or less, otherwise long.

CSHARP · starter
string Label(int minutes)
{
    return minutes.ToString();
}
Check your understanding before moving on.
Knowledge checkQuestion 1

What does var do in C#?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Next: Methods and parameters
Lesson 1 of 300 · 0% of course