C# Type Casting
is and as operators and pattern matching test a type before using it, so a wrong guess never crashes the program. This lesson builds on Data Types.
The examples are complete programs for a dotnet new console project (.NET 8 or later), which uses top-level statements and imports System, System.Linq and System.Collections.Generic automatically. Numbers in the outputs are shown for an English culture; a culture that uses a decimal comma prints 3,5 instead of 3.5.
Implicit Conversions
A conversion is implicit when it can never fail and never loses the magnitude of the value. The compiler inserts it for you: an int fits in a long, every int is a valid double, and every string is an object. These are called widening conversions.
| From | Implicitly converts to |
|---|---|
byte | short, ushort, int, uint, long, ulong, float, double, decimal |
int | long, float, double, decimal |
long | float, double, decimal |
char | ushort, int, uint, long, ulong, float, double, decimal |
float | double |
| any class or struct | its base class, any interface it implements, object |
There is no implicit conversion between double and decimal in either direction, and none from bool to a number: C# does not treat true as 1.
Precision Loss Without a Cast
"Never fails" is not quite "never loses anything". A float holds about 7 significant digits and a double about 15–16, so converting a large int or long to a floating-point type keeps the magnitude but may round the last digits — silently.
// Widening conversions are applied automatically by the compiler.
int count = 42;
long big = count; // int -> long: always exact
double ratio = count; // int -> double: always exact
Console.WriteLine($"{big} {ratio}");
char letter = 'A';
int code = letter; // char -> int: the UTF-16 code
Console.WriteLine(code);
int large = 123_456_789;
float rough = large; // implicit, but float has only ~7 digits
Console.WriteLine((int)rough);
Output:
42 42
65
123456792
Explicit Casts
A narrowing conversion may lose information, so the compiler refuses to do it on its own. Writing the target type in parentheses, (int)value, is your statement that you accept the loss. Know exactly what that loss is:
- Floating point to integer truncates toward zero:
(int)9.99is9and(int)-9.99is-9. UseMath.Round,Math.FloororMath.Ceilingfirst when you want something else. - Integer to a smaller integer keeps only the low bits, so an out-of-range value wraps around:
(byte)300is44, because 300 − 256 = 44. Math.Rounduses banker's rounding by default: a value exactly halfway goes to the even neighbour, so2.5rounds to2and3.5to4. PassMidpointRounding.AwayFromZerofor school rounding.
checked Conversions
Silent wrap-around hides bugs. Inside a checked expression or block, an integer conversion or arithmetic operation that overflows throws an OverflowException instead. You can also turn checking on for a whole project with <CheckForOverflowUnderflow>true</CheckForOverflowUnderflow> in the .csproj, and use unchecked where wrapping is intended, as in hash code calculations.
// Narrowing needs a cast: truncation, wrap-around and rounding rules.
double price = 9.99;
int whole = (int)price; // 9: the fraction is dropped
int rounded = (int)Math.Round(price); // 10
Console.WriteLine($"{whole} {rounded}");
Console.WriteLine($"{Math.Round(2.5)} {Math.Round(3.5)} {Math.Round(2.5, MidpointRounding.AwayFromZero)}");
int big = 300;
byte wrapped = (byte)big; // 44: only the low 8 bits survive
Console.WriteLine(wrapped);
try
{
Console.WriteLine(checked((byte)big)); // throws instead of wrapping
}
catch (OverflowException ex)
{
Console.WriteLine(ex.Message);
}
Output:
9 10
2 4 3
44
Arithmetic operation resulted in an overflow.
Parsing Text
Text that looks like a number is still a string; no cast can turn "42" into 42. Every numeric type, as well as bool, DateTime, Guid and enums, offers two methods:
Parsereturns the value and throws aFormatException(orOverflowException) when the text is not valid. Use it when bad text is a bug.TryParsereturnstrueorfalseand hands the value back through anoutparameter. Use it for anything a user typed or a file contained: invalid input is normal there, and exceptions are slow and noisy for expected cases.
Culture and Invariant Parsing
By default, parsing and formatting follow the current culture of the machine. "3.14" parses as 3.14 in the United States but fails, or means something else, where the decimal separator is a comma. For data exchanged between programs — configuration files, CSV, protocols — always pass CultureInfo.InvariantCulture; keep the current culture for text a person types or reads.
// Parse throws on bad text; TryParse reports failure through its return value.
using System.Globalization;
string[] inputs = { "42", "-7", "3.5", "abc", "" };
foreach (string s in inputs)
{
if (int.TryParse(s, out int n))
Console.WriteLine($"'{s}' -> {n}");
else
Console.WriteLine($"'{s}' -> not an int");
}
double pi = double.Parse("3.14", CultureInfo.InvariantCulture);
Console.WriteLine((pi * 2).ToString(CultureInfo.InvariantCulture));
double german = double.Parse("3,14", CultureInfo.GetCultureInfo("de-DE"));
Console.WriteLine(german.ToString(CultureInfo.InvariantCulture));
bool flag = bool.Parse("True");
DayOfWeek day = Enum.Parse<DayOfWeek>("Friday");
Console.WriteLine($"{flag} {day} {(int)day}");
Output:
'42' -> 42
'-7' -> -7
'3.5' -> not an int
'abc' -> not an int
'' -> not an int
6.28
3.14
True Friday 5
The Convert Class
Convert vs Cast and Parse
System.Convert converts between all the built-in types with one family of methods (ToInt32, ToDouble, ToBoolean, ToString…). It differs from a cast and from Parse in ways worth memorising:
| Expression | Result | Why |
|---|---|---|
(int)2.7 | 2 | a cast truncates |
Convert.ToInt32(2.7) | 3 | Convert rounds |
Convert.ToInt32(2.5) | 2 | …to even at the midpoint |
int.Parse(null) | throws | ArgumentNullException |
Convert.ToInt32((string?)null) | 0 | null becomes the default value |
Convert.ToInt32("ff", 16) | 255 | parses bases 2, 8, 10 and 16 |
// Convert rounds instead of truncating, and maps null to the default value.
Console.WriteLine((int)2.7);
Console.WriteLine(Convert.ToInt32(2.7));
Console.WriteLine(Convert.ToInt32(2.5));
Console.WriteLine(Convert.ToInt32(3.5));
string? missing = null;
Console.WriteLine(Convert.ToInt32(missing));
Console.WriteLine(Convert.ToInt32("ff", 16));
Console.WriteLine(Convert.ToString(255, 2));
Console.WriteLine(Convert.ToBoolean("false"));
Output:
2
3
2
4
0
255
11111111
False
The silent null-to-0 mapping is convenient for legacy data but can hide a missing value. In new code, TryParse usually states the intent better.
Reference Conversions and Patterns
Converting a class to its base type or to an interface (an upcast) is implicit and always safe. Going back down (a downcast) is a claim that the object really is the more specific type; a cast (string)obj throws an InvalidCastException when the claim is wrong. C# gives you three ways to check first:
obj is string stests the type and, if it matches, binds a variablesof that type. This is the everyday tool.obj as stringreturns the object as that type, ornullif it is something else. It works only for reference and nullable types.- A
switchexpression with type patterns handles several types in one place, with optionalwhenconditions. The patterns are tried from top to bottom.
Pattern Matching on Type
// A switch expression tests types top to bottom and binds typed variables.
object?[] items = { "hello", "hi", 42, 3.5, null, new List<int> { 1, 2 } };
foreach (object? item in items)
{
string description = item switch
{
null => "null",
string s when s.Length > 3 => $"long string \"{s}\"",
string s => $"short string \"{s}\"",
int n => $"int {n}, doubled {n * 2}",
double d => $"double {d}",
IEnumerable<int> seq => $"sequence of {seq.Count()} ints",
_ => item.GetType().Name
};
Console.WriteLine(description);
}
Output:
long string "hello"
short string "hi"
int 42, doubled 84
double 3.5
null
sequence of 2 ints
Boxing and Unboxing
Storing a value type such as int in an object variable boxes it: the runtime copies the value into a new object on the heap. Getting it back is unboxing, and it has one strict rule — you must unbox to the exact type that was boxed. A boxed int cannot be unboxed straight to long, even though int converts to long implicitly; unbox first, then convert. Boxing also costs an allocation, which is one reason generic collections like List<int> replaced the old ArrayList.
// Unboxing must name the exact boxed type; as returns null instead of throwing.
object boxed = 42; // boxing: the int is copied into an object
int back = (int)boxed; // unboxing to the exact type: fine
Console.WriteLine(back);
try
{
long wrong = (long)boxed; // a boxed int is not a boxed long
Console.WriteLine(wrong);
}
catch (InvalidCastException)
{
Console.WriteLine("cannot unbox an int as long");
}
long right = (long)(int)boxed; // unbox, then widen
Console.WriteLine(right);
string? text = boxed as string; // no exception: just null
Console.WriteLine(text is null ? "not a string" : text);
Output:
42
cannot unbox an int as long
42
not a string
User-Defined Conversions
implicit and explicit Operators
Your own types can declare conversions with implicit operator and explicit operator. Follow the same rule as the built-in types: make a conversion implicit only when it cannot fail and loses nothing, and explicit when it computes, rounds or can throw. Use them sparingly — a named method such as ToFahrenheit() is often clearer than a cast.
// Conversion operators let a domain type behave like a built-in one.
Celsius boiling = new(100);
Fahrenheit f = (Fahrenheit)boiling; // explicit: a calculation happens
double raw = boiling; // implicit: just unwraps the number
Console.WriteLine($"{boiling.Degrees} C = {f.Degrees} F, raw {raw}");
readonly record struct Celsius(double Degrees)
{
public static implicit operator double(Celsius c) => c.Degrees;
public static explicit operator Fahrenheit(Celsius c) => new(c.Degrees * 9 / 5 + 32);
}
readonly record struct Fahrenheit(double Degrees);
Output:
100 C = 212 F, raw 100
Practice
Choosing a Conversion
| You have | You want | Use |
|---|---|---|
| a number | a wider number | nothing: implicit |
| a number | a narrower number | (T)x, inside checked if overflow is possible |
a double | a rounded integer | (int)Math.Round(x) |
| user or file text | a value | T.TryParse |
| text that must be valid | a value | T.Parse, with CultureInfo.InvariantCulture for data |
an object | a specific type | is T t or a switch pattern |
Exercises
- Read numbers as text from an array, skip the invalid ones with
TryParse, and print the average rounded away from zero to the nearest integer. - Compute
int.MaxValue + 1in a normal and in acheckedcontext, and explain both results. - Write a method
Describe(object? value)that uses aswitchexpression to printbool,DateTimeandint[]values differently; make surenullis handled. - Add an
explicit operator Celsius(Fahrenheit f)to the temperature example and convert 98.6 F back to Celsius.