C# Variables, Data Types, and Control Flow
Introduction
C# is statically typed, meaning every variable has a type known at compile time. This catches many mistakes before your program runs. This tutorial covers the core types, string interpolation, decisions with if/else, and loops.
Prerequisites
- The .NET SDK installed
- A console project you can run with dotnet run
Step-by-Step Guide
Step 1: Declare variables with explicit types
Common types include int, double, decimal (for money), bool, and string. Use var to let the compiler infer the type from the value.
int age = 30;
double height = 1.75;
decimal price = 19.99m;
bool isActive = true;
string name = "Ava";
var city = "London"; // inferred as stringStep 2: Build strings with interpolation
Put $ before a string and wrap expressions in braces to insert values directly.
Console.WriteLine($"{name} is {age} years old.");Step 3: Make decisions with if/else
Conditions must be bool expressions. Chain else if for multiple cases.
int score = 82;
if (score >= 90)
{
Console.WriteLine("Grade A");
}
else if (score >= 80)
{
Console.WriteLine("Grade B");
}
else
{
Console.WriteLine("Keep practicing");
}Step 4: Repeat work with loops
Use for when you know how many times to loop and foreach to walk through a collection.
for (int i = 1; i <= 3; i++)
{
Console.WriteLine("Count: " + i);
}
var languages = new[] { "C#", "Go", "TypeScript" };
foreach (var language in languages)
{
Console.WriteLine(language);
}FAQs
- Why use decimal instead of double for money?
- double is a binary floating-point type and can't represent many decimal fractions exactly. decimal stores decimal values precisely, which avoids rounding surprises in financial calculations.
- Is var the same as dynamic typing?
- No. var is resolved at compile time, so the variable still has one fixed type. Only the keyword you write is shorter.
Summary
Pick the right type for your data, use string interpolation for readable output, and combine if/else with for and foreach to control flow. Types are checked at compile time, which makes errors easier to catch.
Comments
Log in or create a free account to join the discussion.