Variables and Types
C#'s primitive types include int, double, bool, and char — every variable has a declared type, and that type is fixed once declared. Note that bool prints as True or False with a capital letter — a small but genuinely C#-specific detail that trips up people coming from languages that print lowercase true/false.
using System;
class Program {
static void Main() {
int age = 30;
double price = 19.99;
bool isStudent = false;
char grade = 'A';
Console.WriteLine(age + " " + price + " " + isStudent + " " + grade);
}
}30 19.99 False A
var type inference
var lets the compiler infer a variable's type from its initializer. It still produces a fixed, fully static type at compile time — it's not a dynamic type the way it might be in a scripting language.
using System;
class Program {
static void Main() {
var count = 42;
var pi = 3.14159;
Console.WriteLine(count + " " + pi);
}
}42 3.14159
What a real type-mismatch error looks like
C#'s compiler checks that every assignment's types actually line up — assigning a string where an int is expected is a compile error, not something caught later at runtime. This is genuinely what the compiler reports — captured from a real run, not written to look plausible:
using System;
class Program {
static void Main() {
int age = "thirty";
Console.WriteLine(age);
}
}Main.cs(5,19): error CS0029: Cannot implicitly convert type `string' to `int' Compilation failed: 1 error(s), 0 warnings
Nothing runs at all — no output, just the error. Catching this at compile time instead of runtime is one of the main benefits of C#'s static typing.
Next: operators and control flow — if/else, for, while, and switch.
Practice exercise
Declare a variable temperature of type double set to 72.5 and a variable isSunny of type bool set to true. Print them together separated by a space.