C# Tutorial · C# Basics · Lesson 4 of 22
C# Variables and Data Types
Declare typed variables, use var, const and the built-in types.
Declaring variables
int age = 36;
double height = 1.68;
decimal balance = 1250.75m;
bool isActive = true;
char grade = 'A';
string name = "Ada";
var city = "London"; // inferred as string
const double Pi = 3.14159;
Console.WriteLine($"{name}, {age}, {height}, {balance}, {isActive}, {grade}, {city}, {Pi}");
Console.WriteLine($"{int.MaxValue} {0.1 + 0.2} {0.1m + 0.2m}");
Output
Ada, 36, 1.68, 1250.75, True, A, London, 3.14159 2147483647 0.30000000000000004 0.3
Run this on your computer — see “Get Started” for setup.
| Type | Holds |
|---|---|
int, long |
whole numbers |
double |
floating-point numbers |
decimal |
exact decimals — use for money (19.99m) |
bool |
true / false |
char |
one character 'A' |
string |
text |
var lets the compiler infer the type — the variable is still strongly typed. const declares compile-time constants.
Value and reference types
int, double, bool and structs are value types (copied on assignment). Classes, strings and arrays are reference types.
Conversion
double d = 9.78;
int i = (int)d; // explicit cast truncates
long big = i; // implicit widening
int parsed = int.Parse("123");
bool ok = int.TryParse("12abc", out int result);
Console.WriteLine($"{i} {big} {parsed + 1} {ok} {result}");
Console.WriteLine(Convert.ToDouble("2.5") * 2);
Console.WriteLine(7 / 2 + " " + 7 / 2.0);
Output
9 9 124 False 0 5 3 3.5
Run this on your computer — see “Get Started” for setup.
Test yourself
Which type should you use for money in C#?
doublefloatdecimalint
Show answer
Answer: decimal