C#: Variables & Data Types
What you will learn
How to declare variables with explicit types, how var infers the type, and the difference between value types (primitives) and reference types.
C# is statically typed — every variable has a known type at compile time.
string name = "Alice";
int age = 25;
double height = 5.6;
bool isStudent = true;
Type inference with var
var message = "Hello"; // inferred as string
var count = 42; // inferred as int
var price = 19.99m; // inferred as decimal (m suffix)
var tells the compiler to infer the type from the initializer. The type is still fixed — you just don't write it. Use var when the type is obvious (e.g., new List<string>()).
Common types
| Type | Category | Size | Example | Notes |
|---|---|---|---|---|
int |
value | 4 bytes | 42 |
32-bit integer |
long |
value | 8 bytes | 42L |
64-bit integer |
double |
value | 8 bytes | 3.14 |
Double-precision float |
decimal |
value | 16 bytes | 19.99m |
High precision (money) |
bool |
value | 1 byte | true |
|
char |
value | 2 bytes | 'A' |
Unicode character |
string |
reference | object | "hello" |
Immutable text |
| arrays | reference | object | new int[3] |
Common mistakes
- Using
floatwhen you meantdouble—3.14is adoubleliteral by default. Use3.14fforfloat. - Using
decimalwithout themsuffix —19.99is adouble;19.99mis adecimal. - Forgetting that
stringis a reference type — but it's immutable, so it behaves like a value type in practice. - Using
varwhen it obscures the type (e.g.,var result = GetData()— what type isresult?).
Quick check below!