Variables and control flow
C# variables are typed, and branching and loops decide what runs next.
- 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
- 1Declare a string and an inferred var, then print both.
- 2Branch with if/else and add a switch expression.
- 3Repeat with for and foreach loops.
- 4Move a variable into a narrower scope and watch it go out of reach.
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.
Classify a lesson length
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.
string Label(int minutes)
{
return minutes.ToString();
}What does var do in C#?
Make it yours.
Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.
Lock in what you just learned.
Mark this lesson complete to save your place and move one step closer to the certificate.