C# Type Casting

A conversion turns a value of one type into a value of another. C# is statically typed, so the compiler checks every conversion: the safe ones happen implicitly, the risky ones need an explicit cast, and text must be parsed. For objects, the 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.

FromImplicitly converts to
byteshort, ushort, int, uint, long, ulong, float, double, decimal
intlong, float, double, decimal
longfloat, double, decimal
charushort, int, uint, long, ulong, float, double, decimal
floatdouble
any class or structits 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.99 is 9 and (int)-9.99 is -9. Use Math.Round, Math.Floor or Math.Ceiling first when you want something else.
  • Integer to a smaller integer keeps only the low bits, so an out-of-range value wraps around: (byte)300 is 44, because 300 − 256 = 44.
  • Math.Round uses banker's rounding by default: a value exactly halfway goes to the even neighbour, so 2.5 rounds to 2 and 3.5 to 4. Pass MidpointRounding.AwayFromZero for 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:

  • Parse returns the value and throws a FormatException (or OverflowException) when the text is not valid. Use it when bad text is a bug.
  • TryParse returns true or false and hands the value back through an out parameter. 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:

ExpressionResultWhy
(int)2.72a cast truncates
Convert.ToInt32(2.7)3Convert rounds
Convert.ToInt32(2.5)2…to even at the midpoint
int.Parse(null)throwsArgumentNullException
Convert.ToInt32((string?)null)0null becomes the default value
Convert.ToInt32("ff", 16)255parses 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 s tests the type and, if it matches, binds a variable s of that type. This is the everyday tool.
  • obj as string returns the object as that type, or null if it is something else. It works only for reference and nullable types.
  • A switch expression with type patterns handles several types in one place, with optional when conditions. 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 haveYou wantUse
a numbera wider numbernothing: implicit
a numbera narrower number(T)x, inside checked if overflow is possible
a doublea rounded integer(int)Math.Round(x)
user or file texta valueT.TryParse
text that must be valida valueT.Parse, with CultureInfo.InvariantCulture for data
an objecta specific typeis T t or a switch pattern

Exercises

  1. 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.
  2. Compute int.MaxValue + 1 in a normal and in a checked context, and explain both results.
  3. Write a method Describe(object? value) that uses a switch expression to print bool, DateTime and int[] values differently; make sure null is handled.
  4. Add an explicit operator Celsius(Fahrenheit f) to the temperature example and convert 98.6 F back to Celsius.