Variables & Data Types
Lesson 2 โข Beginner Track
What You'll Learn
- Declare variables with explicit types (int, string, double, bool, char)
- Understand value types vs reference types in C#
- Use var for type inference and know when it's appropriate
- Convert between types using casting, Parse, TryParse, and Convert
- Format output with string interpolation, currency, and decimal formatting
- Use verbatim strings (@) and raw string literals for file paths and JSON
๐ก Real-World Analogy
Variables are like labelled containers in a kitchen. A jar labelled "Sugar" (string) holds text, a measuring cup labelled "Cups" (int) holds whole numbers, and a scale labelled "Weight" (double) holds decimals. Each container can only hold one type of ingredient โ you can't pour flour into a measuring cup designed for liquids. C#'s type system works the same way: every variable has a specific type that determines what data it can store.
๐ Common Data Types
| Type | Example | Description | Size |
|---|---|---|---|
| int | int age = 25; | Whole numbers | 4 bytes |
| long | long pop = 8000000000L; | Large whole numbers | 8 bytes |
| double | double pi = 3.14; | Decimal numbers (15-16 digits) | 8 bytes |
| decimal | decimal price = 19.99m; | High precision (financial) | 16 bytes |
| string | string name = "Alice"; | Text (sequence of chars) | Variable |
| char | char grade = 'A'; | Single character | 2 bytes |
| bool | bool active = true; | True or false | 1 byte |
| var | var city = "London"; | Compiler infers type | Depends |
1. Declaring Variables
Every variable in C# must have a type and a name. You can declare and assign in one step, or declare first and assign later. Use descriptive camelCase names like firstName or totalPrice.
Basic Variables & Types
Declare variables of different types and print them.
using System;
class Program
{
static void Main()
{
// Declare and initialize variables
string name = "Alice";
int age = 25;
double height = 5.7;
bool isStudent = true;
char grade = 'A';
// Print using string interpolation
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Age: {age}");
Console.WriteLine($"Height: {height}ft");
Console.WriteLine($"Student: {isStudent}");
Console.WriteLin
...2. Type Casting & Conversion
Sometimes you need to convert between types. Implicit casting happens automatically when it's safe (int โ double). Explicit casting requires the (type) syntax and may lose data. For strings, use Parse, TryParse, or the Convert class.
Type Casting & Conversion
Convert between types safely using casting, Parse, and TryParse.
using System;
class Program
{
static void Main()
{
// Implicit casting (safe โ no data loss)
int myInt = 100;
double myDouble = myInt; // int โ double automatically
Console.WriteLine($"int: {myInt}, double: {myDouble}");
// Explicit casting (may lose data)
double pi = 3.14159;
int rounded = (int)pi; // Truncates to 3
Console.WriteLine($"double: {pi}, int: {rounded}");
// Parse strings to numbers
string a
...3. String Interpolation & Formatting
String interpolation ($"...") is the modern way to embed variables in strings. You can also format numbers as currency (:C), fixed decimals (:F4), or percentages (:P1). Use @"..." for file paths to avoid escaping backslashes.
String Formatting
Master string interpolation, number formatting, and verbatim strings.
using System;
class Program
{
static void Main()
{
string name = "John";
int age = 30;
decimal salary = 55000.75m;
// String concatenation (old way)
Console.WriteLine("Name: " + name + ", Age: " + age);
// String interpolation (modern way)
Console.WriteLine($"Name: {name}, Age: {age}");
// Formatting numbers
Console.WriteLine($"Salary: {salary:C}"); // Currency
Console.WriteLine($"PI: {Math.PI:F4}");
...Pro Tips
- ๐ก Use decimal for money, not double:
doublehas floating-point rounding errors.decimal price = 19.99m;is precise for financial calculations. - ๐ก Prefer TryParse over Parse:
int.Parse("abc")throws an exception.int.TryParse("abc", out int result)returns false safely. - ๐ก Use var wisely:
var name = "Alice";is fine when the type is obvious. Avoidvar result = GetData();when the return type isn't clear. - ๐ก Constants use const:
const double PI = 3.14159;โ the value can never change and must be known at compile time.
Common Mistakes
- Forgetting the m suffix for decimal:
decimal price = 19.99;won't compile โ you need19.99m. - Integer division surprise:
int result = 7 / 2;gives3, not3.5. Cast to double first:(double)7 / 2. - Using single quotes for strings:
'hello'is invalid โ strings use double quotes. Single quotes are forcharonly:'A'. - Uninitialized variables: Local variables must be assigned before use.
int x; Console.WriteLine(x);won't compile. - Overflow without checking:
int.MaxValue + 1wraps around silently. Usecheckedblocks to catch overflow errors.
๐ Lesson Complete
- โ
Variables store data with a specific type:
int,string,double,bool,char,decimal - โ
Use
varfor type inference when the type is obvious from the right side - โ
Implicit casting is automatic and safe; explicit casting uses
(type)and may lose data - โ
TryParseis safer thanParsefor converting strings to numbers - โ
String interpolation
$"..."with format specifiers (:C,:F2,:P1) for clean output - โ
Use
decimalfor financial values,constfor compile-time constants - โ Next lesson: Operators โ arithmetic, comparison, and logical operations
Sign up for free to track which lessons you've completed and get learning reminders.