CSharp · Console
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("Implicit and explicit conversion");
int wholeNumber = 42;
double asDouble = wholeNumber;
double pi = 3.9;
int truncated = (int)pi;
Console.WriteLine($"int -> double (implicit): {asDouble}");
Console.WriteLine($"(int)3.9 (explicit): {truncated}");
Console.WriteLine();
Console.WriteLine("Narrowing casts can silently lose data");
int tooBig = 300;
byte wrapped = (byte)tooBig;
Console.WriteLine($"(byte)300 (unchecked): {wrapped}");
try
{
byte guarded = checked((byte)tooBig);
Console.WriteLine($"checked (byte)300: {guarded}");
}
catch (OverflowException ex)
{
Console.WriteLine($"checked (byte)300 threw: {ex.GetType().Name}");
}
Console.WriteLine();
Console.WriteLine("Parse vs TryParse vs Convert");
try
{
int.Parse("abc");
}
catch (FormatException ex)
{
Console.WriteLine($"int.Parse(\"abc\") threw: {ex.GetType().Name}");
}
string? missing = null;
try
{
int.Parse(missing);
}
catch (ArgumentNullException ex)
{
Console.WriteLine($"int.Parse(null) threw: {ex.GetType().Name}");
}
int converted = Convert.ToInt32(missing);
Console.WriteLine($"Convert.ToInt32(null): {converted}");
bool ok = int.TryParse("abc", out int safeResult);
Console.WriteLine($"int.TryParse(\"abc\"): ok={ok}, result={safeResult}");
Console.WriteLine();
Console.WriteLine("Reference type conversion: cast vs as vs is");
object boxedNumber = 42;
try
{
string forced = (string)boxedNumber;
}
catch (InvalidCastException ex)
{
Console.WriteLine($"(string)boxedNumber threw: {ex.GetType().Name}");
}
string? safe = boxedNumber as string;
Console.WriteLine($"boxedNumber as string: {safe ?? "null"}");
if (boxedNumber is int number)
{
Console.WriteLine($"boxedNumber is int: {number}");
}
}
}