Syntax and types
โ Report an issue with this lessonstring name = "Ada";
int age = 28;
double price = 29.99;
bool isFree = false;
Console.WriteLine($"{name} is {age} years old");
C# is statically typed like Java, but with type inference via
var when the type is obvious from context:
var courses = new List<string>(); // inferred as List<string>
var count = 5; // inferred as int
var doesn't make C# dynamically typed -- the compiler
still pins down a single concrete type at compile time, it's just inferred
rather than written out. var x = GetCourse(); is exactly as
strict as Course x = GetCourse();; the difference is purely
how much you type. Use var when the right-hand side already
makes the type obvious, and spell out the type explicitly when it
wouldn't be (e.g. int result = ComputeScore(); when
ComputeScore's return type isn't clear from the name).
C# distinguishes value types from reference types, which matters for
how assignment behaves. int, double,
bool, and structs are value types -- assigning
one variable to another copies the value:
int a = 5;
int b = a; // b is an independent copy
b = 10;
Console.WriteLine(a); // still 5
string, arrays, and any class are reference
types -- assignment copies the reference, so both variables point at the
same underlying object:
var list1 = new List<int> { 1, 2, 3 };
var list2 = list1; // same list, not a copy
list2.Add(4);
Console.WriteLine(list1.Count); // 4 -- list1 sees list2's change too
String is a special case worth calling out: it's a reference type, but
it's immutable -- every operation that looks like it modifies a
string (ToUpper(), Replace(...),
Substring(...)) actually returns a brand-new string rather
than changing the original. This is why str.ToUpper(); on
its own line, without assigning the result somewhere, silently does
nothing useful.
Try it yourself
Run your code and get it working before marking this lesson complete.
8 more lessons โ including Capstone project: a course catalog console app โ plus a certificate are waiting.
Unlock the full course โ $149.99