You are viewing a free preview of this lesson.
Subscribe to unlock all 10 lessons in this course and every other course on LearningBro.
C# is a statically typed language — every variable has a type known at compile time. This lesson covers the type system, value types, reference types, strings, and nullable types.
Variables in C# are declared with a type followed by a name:
int age = 30;
string name = "Alice";
double price = 19.99;
bool isActive = true;
The var keyword lets the compiler infer the type from the assigned value:
var age = 30; // int
var name = "Alice"; // string
var price = 19.99; // double
var isActive = true; // bool
Tip: Use
varwhen the type is obvious from the right-hand side. Use explicit types when clarity is needed.
| Category | Stored In | Assignment | Default | Examples |
|---|---|---|---|---|
| Value types | Stack | Copies the value | 0, false, etc. | int, double, bool, struct, enum |
| Reference types | Heap | Copies the reference | null | string, class, array, object |
// Value type — independent copies
int a = 10;
int b = a;
b = 20;
Console.WriteLine(a); // 10 (unchanged)
// Reference type — shared reference
int[] arr1 = { 1, 2, 3 };
int[] arr2 = arr1;
arr2[0] = 99;
Console.WriteLine(arr1[0]); // 99 (changed!)
| Type | Size | Range |
|---|---|---|
byte | 8-bit | 0 to 255 |
short | 16-bit | -32,768 to 32,767 |
int | 32-bit | -2.1 billion to 2.1 billion |
long | 64-bit | -9.2 quintillion to 9.2 quintillion |
Each has an unsigned variant: sbyte, ushort, uint, ulong.
int count = 42;
long bigNumber = 9_000_000_000L; // underscore separators for readability
byte flags = 0b_1010_0011; // binary literal
int hex = 0xFF; // hexadecimal literal
| Type | Size | Precision | Suffix |
|---|---|---|---|
float | 32-bit | ~7 digits | f |
double | 64-bit | ~15 digits | (default) |
decimal | 128-bit | ~28 digits | m |
float temperature = 36.6f;
double pi = 3.14159265358979;
decimal salary = 75_000.50m; // Use decimal for money!
Tip: Always use
decimalfor financial calculations to avoid floating-point rounding errors.
bool isLoggedIn = true;
bool hasPermission = false;
C# does not allow implicit conversion between integers and booleans (unlike C/C++).
Subscribe to continue reading
Get full access to this lesson and all 10 lessons in this course.