Day 2: Variables, Types, & Conversion
Welcome to Day 2. Today, we look at the foundation of C#: Types.
C# is a statically typed language. This means you must declare the type of a variable before you can use it, and the compiler checks these types at compile-time instead of runtime. This catches tons of bugs before your code even runs!
Basic Types
Here are the most common primitive types you’ll use daily:
// Integers (whole numbers)
int age = 30;
// Floating-point (decimals). Note the 'm' suffix for precise decimal (perfect for money)
double height = 1.75;
decimal bankBalance = 1500.50m;
// Booleans
bool isAwesome = true;
// Characters and Strings
char grade = 'A'; // Single quotes
string name = "Alice"; // Double quotes
The ‘var’ Keyword
While C# is strongly typed, you don’t always have to explicitly write the type. If the compiler can figure it out from the right side of the equals sign, you can use var.
// The compiler knows this is an int
var score = 100;
// The compiler knows this is a string
var message = "It works!";
// This is an ERROR. You can't just declare 'var' without assigning it!
// var x;
Under the hood, score is strictly an int. You cannot later assign score = "Hello"; — the compiler will yell at you.
Type Conversion
Often, you need to change a value from one type to another (e.g., converting user string input into a number).
1. Implicit Conversion (Safe)
Happens automatically when moving from a smaller type to a larger type.
int myInt = 10;
double myDouble = myInt; // Safe. 10 becomes 10.0
2. Explicit Conversion / Casting (Potential data loss)
Requires you to explicitly tell the compiler “I know what I’m doing.”
double pi = 3.14;
int rounded = (int)pi; // 'rounded' is 3. The .14 is lost!
3. Parsing (String to Type)
Used heavily when getting input.
string input = "50";
int parsedNumber = int.Parse(input);
// Safer approach (returns true/false instead of crashing if it fails!)
if (int.TryParse("not an int", out int result))
{
Console.WriteLine($"Success! Result: {result}");
}
else
{
Console.WriteLine("That was not a valid number.");
}
Challenge for Day 2
Write a program that prompts the user for two numbers (as strings), parses them into integers using TryParse, adds them together, and prints the result.
Tomorrow: Control Flow.