404 Not Found

404 Not Found


nginx

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

Example

CSHARP
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}");
▶ Try it Yourself
TEXT
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

CSHARP
TargetType variable = (TargetType)value;

Example

CSHARP
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}");
▶ Try it Yourself
TEXT
(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

CSHARP
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}");
▶ Try it Yourself
TEXT
ToInt32: 42
ToDouble: 3.14
ToString: 42
ToBoolean("0"): False
ToBoolean(1): True

Tip: Convert.ToBoolean only recognizes "True" and "False" for strings. For numeric values, non-zero is true and zero is false.

Parse and TryParse

Parse Method

Parse converts a string to the target type and throws a FormatException if the format is invalid.

Example

CSHARP
int a = int.Parse("42");
double b = double.Parse("3.14");
Console.WriteLine($"int.Parse: {a}");
Console.WriteLine($"double.Parse: {b}");
▶ Try it Yourself
TEXT
int.Parse: 42
double.Parse: 3.14
CSHARP
try
{
    int bad = int.Parse("hello");
}
catch (FormatException ex)
{
    Console.WriteLine($"Parse failed: {ex.Message}");
}
TEXT
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

CSHARP
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}");
}
▶ Try it Yourself
TEXT
Parse succeeded: 42
Parse failed, result2 = 0

Tip: Prefer TryParse when 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

CSHARP
int value = 42;
object boxed = value;
Console.WriteLine($"Boxed: {boxed}, Type: {boxed.GetType()}");
▶ Try it Yourself
TEXT
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

CSHARP
object boxed = 42;
int unboxed = (int)boxed;
Console.WriteLine($"Unboxed: {unboxed}");
▶ Try it Yourself
TEXT
Unboxed: 42
CSHARP
object boxed = 42;
try
{
    double wrong = (double)boxed;
}
catch (InvalidCastException ex)
{
    Console.WriteLine($"Unbox type mismatch: {ex.Message}");
}
TEXT
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 InvalidCastException is thrown.

Common Type Conversion Pitfalls

Floating-Point to Integer Precision Loss

CSHARP
double d = 9.99;
int i = (int)d;
Console.WriteLine($"9.99 → {i}");
TEXT
9.99 → 9

Overflow from Wide to Narrow Type

CSHARP
long big = 5000000000L;
int small = (int)big;
Console.WriteLine($"5000000000L → {small}");
TEXT
5000000000L → 705032704

Parse Throwing on Invalid Strings

CSHARP
try
{
    int n = int.Parse("3.14");
}
catch (FormatException)
{
    Console.WriteLine("Cannot parse \"3.14\" as int");
}
TEXT
Cannot parse "3.14" as int

Tip - Best practices to avoid pitfalls: check data ranges before converting; prefer TryParse; use the checked keyword for overflow scenarios.

❓ FAQ

Q Does implicit conversion never lose data?
A Correct. Implicit conversion only occurs along safe paths where no precision or range is lost. Q: What is the difference between Convert.ToInt32 and (int) cast? A: (int) truncates directly, while Convert.ToInt32 rounds floating-point values using banker's rounding. Q: How do boxing and unboxing affect performance? A: Boxing allocates memory on the heap, and unboxing requires a type check and value copy. Frequent operations degrade performance. Q: Which is better: int.Parse or Convert.ToInt32? A: For string input they behave similarly, but Convert.ToInt32 returns 0 for null, while int.Parse throws an exception. Q: What is the value of the out parameter when TryParse fails? A: It is set to the default value of the type, e.g., 0 for int.

📖 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

  1. Write a program that implicitly converts a short value of 32767 to int and explicitly casts an int value of 32768 to short, and observe the results
  2. Use Convert.ToInt32 to convert 2.5 and 3.5, and verify banker's rounding behavior
  3. Write a method that accepts a string parameter, uses TryParse to safely parse it as an int, returns the parsed value on success, or -1 on failure
  4. Write code that demonstrates boxing and unboxing, then deliberately unbox with the wrong type and catch the InvalidCastException
  5. Wrap an overflowing int cast with the checked keyword and observe whether an OverflowException is thrown
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏