Type Conversion, Parse(), TryParse() & Boxing/Unboxing Masterclass
๐ Covered in this chapter:
Implicit Conversion ยท Explicit Casting ยท Convert Class ยท int.Parse() ยท int.TryParse() ยท out Parameter ยท String to Number ยท Number to String ยท Boxing & Unboxing
Welcome to Phase 2 (Chapter 6): C# Type Conversion, Casting, Parse(), TryParse() & Boxing/Unboxing Masterclass! Type conversion converts a value from one data type to another. C# provides Implicit conversion (automatic safe widening), Explicit casting (manual narrowing), Convert class helper methods, int.Parse(), and the fail-safe int.TryParse() pattern.
1Implicit Conversion vs Explicit Casting
C# โ Conversion & Casting
โถ Run in Compiler
// 1. Implicit Conversion (Automatic โ small type to larger type, no data loss)
int numInt = 100;
long numLong = numInt; // int -> long (safe)
double numDouble = numLong; // long -> double (safe)
Console.WriteLine($"Implicit Double: {numDouble}");
// 2. Explicit Casting (Manual โ larger type to smaller type, potential truncation!)
double pi = 3.14159;
int truncatedPi = (int)pi; // Cast double to int: truncates fractional part
Console.WriteLine($"Explicit Cast Int: {truncatedPi}"); // Output: 3
2Convert Class vs Parse() vs TryParse()
| Method | Null Input Behavior | Invalid Format Behavior | Best Used For |
|---|---|---|---|
Convert.ToInt32(str) | Returns 0 (does not throw) | Throws FormatException | When null inputs should safely evaluate to 0 |
int.Parse(str) | Throws ArgumentNullException | Throws FormatException | When string is guaranteed to be a valid number |
int.TryParse(str, out int val) | Returns false (NO EXCEPTION THROWN!) | Returns false (NO EXCEPTION THROWN!) | Best Practice: User input validation from Console or APIs |
C# โ Fail-Safe TryParse Pattern
โถ Run in Compiler
string input = "25";
// TryParse safely attempts conversion without throwing exceptions
if (int.TryParse(input, out int age))
{
Console.WriteLine($"Conversion Successful! Age: {age}");
}
else
{
Console.WriteLine("Invalid age input. Please enter a valid number.");
}
3Boxing and Unboxing
Boxing is converting a Value Type (like int) to a Reference Type (object), allocating memory on the Heap. Unboxing is extracting the Value Type back from the Reference Type object.
Boxing & Unboxing Memory Pipeline:
int val = 42; โโ[ BOXING ]โโโบ Heap Object: [ System.Int32 : 42 ]
(Stack Value) (Allocated on Heap)
โ
int y = (int)obj; โโ[ UNBOXING ]โโโโโโโโโโโโโโ
(Copied back to Stack)
C# โ Boxing & Unboxing
โถ Run in Compiler
int val = 123; // Value type on Stack
// 1. Boxing: Value Type -> Reference Type (object)
object boxedObj = val; // Allocates memory on Heap!
// 2. Unboxing: Reference Type -> Value Type (explicit cast required)
int unboxedVal = (int)boxedObj; // Extracted back to Stack
Console.WriteLine($"Boxed: {boxedObj}, Unboxed: {unboxedVal}");
4Technical FAQs
Q1: Why is TryParse() preferred over Parse() in production code?
Parse() throws heavy exceptions on invalid input, which damages performance and causes application crashes if uncaught. TryParse() returns a boolean flag safely without throwing exceptions.