C# Type Casting
Conversion changes a value from one type to another. C# offers implicit and explicit casts, parsing helpers, and safe
as/is patterns.
Implicit Conversion
Widening conversions never lose data, so C# applies them automatically.
int i = 42;
long l = i; // implicit: int to long
double d = i; // implicit: int to double
Explicit Cast
Narrowing can lose data, so it requires a cast operator. Fractional parts are truncated.
double d = 3.9;
int i = (int)d; // 3 — truncates, no rounding
Parse Methods
Parse converts a string; TryParse returns success instead of throwing.
int n = int.Parse("42");
double x = double.Parse("3.14");
if (int.TryParse("maybe", out int result))
{
Console.WriteLine(result);
}
else
{
Console.WriteLine("not a number");
}
Convert Class
Convert converts between many types and takes care of culture and rounding details.
int n = Convert.ToInt32("42");
string s = Convert.ToString(123);
bool b = Convert.ToBoolean("true");
Safe Casting
as Operator
as returns null on failure instead of throwing. It works with reference types (and nullable value types).
object o = "hello";
string s = o as string; // "hello"; null if not a string
if (s != null)
{
Console.WriteLine(s);
}
is Operator
is tests a type and binds a typed variable in one step.
object o = 42;
if (o is int number)
{
Console.WriteLine(number + 1); // 43
}
Pattern Casting
Combine a type test with a condition in a single pattern.
object o = "hello world";
if (o is string text && text.Length > 0)
{
Console.WriteLine(text.ToUpper()); // HELLO WORLD
}