Type Conversion
Implicit Conversion
Implicit conversion is performed automatically by the compiler without any extra syntax. It occurs when assigning from a narrower type to a wider type and never loses data.
Conversion Rules
int→longint→doublefloat→double- Any type →
string(viaToString())
Example
int a = 100;
long b = a;
int c = 42;
double d = c;
float e = 3.14f;
double f = e;
int g = 99;
string h = g.ToString();
Console.WriteLine($"int→long: {b}");
Console.WriteLine($"int→double: {d}");
Console.WriteLine($"float→double: {f}");
Console.WriteLine($"int→string: {h}");
int→long: 100
int→double: 42
float→double: 3.14
int→string: 99
Explicit Conversion
Explicit conversion requires a cast syntax, placing the target type in parentheses before the value. It occurs when assigning from a wider type to a narrower type and may lose data.
Syntax
TargetType variable = (TargetType)value;
Example
double pi = 3.14;
int truncated = (int)pi;
int number = 42;
double widened = (double)number;
long big = 3000000000L;
int overflow = (int)big;
Console.WriteLine($"(int)3.14 → {truncated}");
Console.WriteLine($"(double)42 → {widened}");
Console.WriteLine($"(int)3000000000L → {overflow}");
(int)3.14 → 3
(double)42 → 42
(int)3000000000L → -1294967296
Warning: Explicit conversion may cause precision loss or overflow. Always verify the data range before casting.
Convert Class
The System.Convert class provides static methods for converting between various base types. It is safer and more expressive than a direct cast.
Common Methods
| Method | Description |
|---|---|
Convert.ToInt32 |
Converts to int |
Convert.ToDouble |
Converts to double |
Convert.ToString |
Converts to string |
Convert.ToBoolean |
Converts to bool |
Example
string s1 = "42";
string s2 = "3.14";
string s3 = "0";
int n1 = Convert.ToInt32(s1);
double n2 = Convert.ToDouble(s2);
string n3 = Convert.ToString(n1);
bool n4 = Convert.ToBoolean(s3);
bool n5 = Convert.ToBoolean(1);
Console.WriteLine($"ToInt32: {n1}");
Console.WriteLine($"ToDouble: {n2}");
Console.WriteLine($"ToString: {n3}");
Console.WriteLine($"ToBoolean(\"0\"): {n4}");
Console.WriteLine($"ToBoolean(1): {n5}");
ToInt32: 42
ToDouble: 3.14
ToString: 42
ToBoolean("0"): False
ToBoolean(1): True
Tip:
Convert.ToBooleanonly recognizes"True"and"False"for strings. For numeric values, non-zero istrueand zero isfalse.
Parse and TryParse
Parse Method
Parse converts a string to the target type and throws a FormatException if the format is invalid.
Example
int a = int.Parse("42");
double b = double.Parse("3.14");
Console.WriteLine($"int.Parse: {a}");
Console.WriteLine($"double.Parse: {b}");
int.Parse: 42
double.Parse: 3.14
try
{
int bad = int.Parse("hello");
}
catch (FormatException ex)
{
Console.WriteLine($"Parse failed: {ex.Message}");
}
Parse failed: Input string was not in a correct format.
TryParse Method
TryParse never throws an exception. It returns a bool indicating success, and outputs the parsed value via an out parameter.
Example
if (int.TryParse("42", out int result1))
{
Console.WriteLine($"Parse succeeded: {result1}");
}
if (!int.TryParse("abc", out int result2))
{
Console.WriteLine($"Parse failed, result2 = {result2}");
}
Parse succeeded: 42
Parse failed, result2 = 0
Tip: Prefer
TryParsewhen dealing with unreliable input such as user data, to avoid the performance cost of exceptions.
Boxing and Unboxing
Boxing
Boxing is the process of converting a value type to an object reference type. The value is copied from the stack to the heap, incurring a memory allocation.
Example
int value = 42;
object boxed = value;
Console.WriteLine($"Boxed: {boxed}, Type: {boxed.GetType()}");
Boxed: 42, Type: System.Int32
Unboxing
Unboxing is the process of explicitly casting an object reference back to a value type. It requires an explicit cast, and a type mismatch throws an InvalidCastException.
Example
object boxed = 42;
int unboxed = (int)boxed;
Console.WriteLine($"Unboxed: {unboxed}");
Unboxed: 42
object boxed = 42;
try
{
double wrong = (double)boxed;
}
catch (InvalidCastException ex)
{
Console.WriteLine($"Unbox type mismatch: {ex.Message}");
}
Unbox type mismatch: Specified cast is not valid.
Warning: The target type in an unboxing operation must exactly match the original boxed type, otherwise an
InvalidCastExceptionis thrown.
Common Type Conversion Pitfalls
Floating-Point to Integer Precision Loss
double d = 9.99;
int i = (int)d;
Console.WriteLine($"9.99 → {i}");
9.99 → 9
Overflow from Wide to Narrow Type
long big = 5000000000L;
int small = (int)big;
Console.WriteLine($"5000000000L → {small}");
5000000000L → 705032704
Parse Throwing on Invalid Strings
try
{
int n = int.Parse("3.14");
}
catch (FormatException)
{
Console.WriteLine("Cannot parse \"3.14\" as int");
}
Cannot parse "3.14" as int
Tip - Best practices to avoid pitfalls: check data ranges before converting; prefer
TryParse; use thecheckedkeyword for overflow scenarios.
❓ FAQ
📖 Summary
- Implicit conversion goes from narrower to wider types and is safe and automatic
- Explicit conversion uses cast syntax and may lose precision or overflow
- The Convert class provides safe cross-type conversion methods
- Parse directly parses strings and throws on failure; TryParse safely returns a boolean
- Boxing wraps a value type as a heap-allocated object; unboxing requires an exact type match
- Prefer TryParse in production code to avoid exceptions and implicit boxing
📝 Exercises
- Write a program that implicitly converts a
shortvalue of 32767 tointand explicitly casts anintvalue of 32768 toshort, and observe the results - Use
Convert.ToInt32to convert 2.5 and 3.5, and verify banker's rounding behavior - Write a method that accepts a string parameter, uses
TryParseto safely parse it as anint, returns the parsed value on success, or -1 on failure - Write code that demonstrates boxing and unboxing, then deliberately unbox with the wrong type and catch the
InvalidCastException - Wrap an overflowing
intcast with thecheckedkeyword and observe whether anOverflowExceptionis thrown



