Type Casting — Reshaping the Blueprint Materials
15 XPMedium
Ctrl+Enter RunCtrl+S Save
🔄 Reshaping Materials
Sometimes the .NET Architect receives a steel beam that's just slightly the wrong shape. It needs to be reshaped — carefully — to fit the design. That's type casting in C#: converting a value from one data type to another.
There are two fundamental kinds: implicit (safe, automatic) and explicit (risky, manual). Understanding the difference is like knowing when you can bend a wire with your fingers versus when you need heavy machinery.
✅ Implicit Casting (Widening) — Safe & Automatic
When you go from a smaller type to a larger type, no data is lost. C# does this automatically — no special syntax needed.
int floors = 42;
double preciseFloors = floors; // int → double (automatic)
Console.WriteLine(preciseFloors); // 42
// Widening chain: byte → short → int → long → float → double
⚠️ Explicit Casting (Narrowing) — Manual & Risky
Going from a larger type to a smaller type can lose data. You must explicitly tell C# you accept the risk by putting the target type in parentheses.
double price = 3.99;
int roundedPrice = (int)price; // Truncates! Not rounds → 3
Console.WriteLine(roundedPrice); // 3
long bigNumber = 300;
int smaller = (int)bigNumber; // Works if value fits in int
🔧 The Convert Class & Parse Methods
For conversions between unrelated types (like string to int), use the Convert class or the type's Parse / TryParse methods.
// string → int
string input = "100";
int parsed = int.Parse(input); // Throws if invalid
int converted = Convert.ToInt32(input); // Also throws if invalid
// Safe parsing with TryParse — no exceptions!
bool success = int.TryParse("abc", out int result);
// success = false, result = 0
// Convert between other types
bool flag = Convert.ToBoolean(1); // True (non-zero = true)
string text = Convert.ToString(42); // "42"
📦 Boxing & Unboxing (Preview)
In C#, value types (int, double, bool) live on the stack. Reference types (string, arrays, objects) live on the heap. Boxing wraps a value type in an object on the heap; unboxing extracts it back. This matters for performance — avoid unnecessary boxing in hot loops.
int num = 42;
object boxed = num; // Boxing: int → object (heap allocation)
int unboxed = (int)boxed; // Unboxing: object → int
🛡️ Checked & Unchecked Overflow
By default, integer overflow wraps around silently. Use checked to throw an exception on overflow instead:
// Unchecked (default) — wraps around
int max = int.MaxValue;
int overflow = max + 1; // -2147483648 (wraps!)
// Checked — throws OverflowException
// int safe = checked(max + 1); // throws!
📋 Instructions
### Your Mission
The Architect needs to convert materials between different measurement systems. Practice all four casting techniques:
1. **Implicit cast:** Assign an `int` value `42` to a `double` variable and print it.
2. **Explicit cast:** Cast the `double` value `3.99` to an `int` and print it.
3. **Parse:** Parse the string `"100"` into an `int` using `int.Parse()` and print it.
4. **Convert:** Convert the `int` value `1` to a `bool` using `Convert.ToBoolean()` and print it.
Expected output:
```
Implicit: 42
Explicit: 3
Parsed: 100
Converted: True
```
For implicit: double d = 42; — For explicit: int i = (int)3.99; — For parse: int p = int.Parse("100"); — For convert: bool b = Convert.ToBoolean(1); Then print each with the matching label.