ZetCode

Type conversions in C#

last modified November 15, 2026

This article shows how values are converted between types in C#: implicit and explicit numeric conversions, numeric promotion, overflow checking, boxing, reference conversions, user-defined conversions, and conversions from strings.

A type conversion creates a value of one type from a value of another type. C# distinguishes two kinds of conversions:

Kind Behaviour
Implicit numeric Automatic widening, e.g. int to long; long to double may lose precision
Explicit numeric Cast required; truncates, wraps, or saturates
Boxing, unboxing Value type to object or interface and back
Reference Implicit upcast, explicit downcast; is and as
User-defined implicit operator and explicit operator
String Not a conversion: Parse, TryParse, ToString, Convert

Numeric promotion

Arithmetic operators are defined only for int, uint, long, ulong, float, double, and decimal. Operands of the smaller types byte, sbyte, short, ushort, and char are promoted to int. When the operands have different types, the narrower one is converted to the wider one.

Operation Result type
byte + byte, short + short, char + charint
int + longlong
uint + intlong
long + float, float + intfloat
float + doubledouble
int + decimaldecimal
Program.cs
byte b = 10;
short s = 20;
char c = 'A';
int i = 30;
long l = 100L;
float f = 5.5f;
double d = 2.2;
decimal m = 1.5m;

Show("byte + byte", b + b);
Show("short + short", s + s);
Show("char + char", c + c);
Show("byte + short", b + s);
Show("int + long", i + l);
Show("long + float", l + f);
Show("float + int", f + i);
Show("float + double", f + d);
Show("int + decimal", i + m);
Show("uint + int", 5u + i);
Show("ulong + uint", 5ul + 5u);

static void Show(string expr, object result)
{
    Console.WriteLine($"{expr,-15} {result.GetType().Name,-8} {result}");
}

The program prints the type and value of the results of mixed expressions.

static void Show(string expr, object result)
{
    Console.WriteLine($"{expr,-15} {result.GetType().Name,-8} {result}");
}

The result is passed as object, so GetType returns the run-time type of the expression. The type names are the .NET names: Int32 is int, Int64 is long, and Single is float.

Show("char + char", c + c);

Characters are added as their numeric codes: 65 + 65.

Show("uint + int", 5u + i);

No 32-bit type can hold all values of both uint and int, so the operands are promoted to long. There is no such type for ulong and a signed variable: their sum is error CS0034, an ambiguous operator.

$ dotnet run
byte + byte     Int32    20
short + short   Int32    40
char + char     Int32    130
byte + short    Int32    30
int + long      Int64    130
long + float    Single   105.5
float + int     Single   35.5
float + double  Double   7.7
int + decimal   Decimal  31.5
uint + int      Int64    35
ulong + uint    UInt64   10

Implicit conversions

Implicit conversions widen a value to a type with a larger range, such as byte to short or int to long. Conversions from int and long to float, and from long to double, are implicit too, although they can lose precision: float has 24 significant bits and double 53.

Program.cs
byte b = 100;
short s = b;
int i = s;
long l = i;
double d = l;

Console.WriteLine($"byte: {b}, short: {s}, int: {i}, long: {l}, double: {d}");

int big = 16_777_217;
float f = big;
Console.WriteLine($"int {big} -> float {f:F0}");

long huge = 9_007_199_254_740_993;
double d2 = huge;
Console.WriteLine($"long {huge} -> double {d2:F0}");

We widen a value step by step and then convert large integers to floating-point types.

int big = 16_777_217;
float f = big;

16,777,217 is 224 + 1, which needs 25 significant bits. The conversion rounds it to the nearest float, 16,777,216.

long huge = 9_007_199_254_740_993;
double d2 = huge;

The same happens with double for 253 + 1. The compiler gives no warning in either case.

$ dotnet run
byte: 100, short: 100, int: 100, long: 100, double: 100
int 16777217 -> float 16777216
long 9007199254740993 -> double 9007199254740992

Explicit conversions

Conversions that may lose the magnitude of the value require a cast.

Program.cs
double d = 123.789;
int i = (int)d;
Console.WriteLine($"(int){d} = {i}");

int n = 300;
byte b = (byte)n;
Console.WriteLine($"(byte){n} = {b}");

int neg = -1;
uint u = (uint)neg;
Console.WriteLine($"(uint){neg} = {u}");

long l = 5_000_000_000;
Console.WriteLine($"(int){l} = {(int)l}");

double nan = double.NaN;
Console.WriteLine($"(int)NaN = {(int)nan}");
double huge = 1e20;
Console.WriteLine($"(int)1e20 = {(int)huge}");

decimal m = 2.99m;
Console.WriteLine($"(int){m} = {(int)m}");

We cast floating-point and integer values to narrower types.

int i = (int)d;

A cast from double to int truncates the fraction toward zero; it does not round.

byte b = (byte)n;

A cast between integer types keeps the low-order bits: 300 is 0x12C, and the low byte 0x2C is 44. Casting -1 to uint reinterprets its bits as 4,294,967,295.

double huge = 1e20;
Console.WriteLine($"(int)1e20 = {(int)huge}");

Since .NET 9, casts from floating-point to integer types saturate on all platforms: values out of range become the minimum or maximum of the target type and NaN becomes 0. The value is in a variable on purpose; casting the constant 1e20 directly is a compile-time error CS0221, because constant expressions are always checked.

$ dotnet run
(int)123.789 = 123
(byte)300 = 44
(uint)-1 = 4294967295
(int)5000000000 = 705032704
(int)NaN = 0
(int)1e20 = 2147483647
(int)2.99 = 2

Checked and unchecked contexts

Integer arithmetic and integer casts that overflow wrap around by default. In a checked context, they throw an OverflowException. The default can be changed for a whole project with the CheckForOverflowUnderflow property.

Program.cs
int max = int.MaxValue;

int wrapped = unchecked(max + 1);
Console.WriteLine($"unchecked: {wrapped}");

try
{
    int result = checked(max + 1);
    Console.WriteLine(result);
}
catch (OverflowException e)
{
    Console.WriteLine($"checked: {e.Message}");
}

int n = 300;

try
{
    checked
    {
        byte b = (byte)n;
        Console.WriteLine(b);
    }
}
catch (OverflowException)
{
    Console.WriteLine($"checked cast of {n} to byte: OverflowException");
}

Console.WriteLine($"default context: {max + 1}");

We overflow an addition and a cast in both contexts.

int wrapped = unchecked(max + 1);

In an unchecked context, int.MaxValue + 1 wraps to int.MinValue.

int result = checked(max + 1);

The checked expression throws instead.

checked
{
    byte b = (byte)n;
    Console.WriteLine(b);
}

The checked statement applies to all operations in its block, including casts.

$ dotnet run
unchecked: -2147483648
checked: Arithmetic operation resulted in an overflow.
checked cast of 300 to byte: OverflowException
default context: -2147483648

Compound assignment

Because of numeric promotion, the sum of two byte values is an int. Assigning it to a byte variable without a cast is error CS0266. Compound assignment operators such as += and the ++ operator include the cast back to the type of the variable.

Program.cs
byte b1 = 100;
byte b2 = 200;

int sum = b1 + b2;
Console.WriteLine($"b1 + b2 = {sum}");

byte bsum = (byte)(b1 + b2);
Console.WriteLine($"(byte)(b1 + b2) = {bsum}");

byte counter = 250;
counter += 10;
Console.WriteLine($"250 += 10 -> {counter}");

counter++;
Console.WriteLine($"after ++ -> {counter}");

short sh = 10;
sh *= 2;
Console.WriteLine($"short *= 2 -> {sh} ({sh.GetType().Name})");

We add bytes and increment a byte counter past its maximum.

byte bsum = (byte)(b1 + b2);

The explicit cast keeps the low byte of 300, which is 44.

counter += 10;

The statement compiles without a cast because it means counter = (byte)(counter + 10). The cast is hidden, and so is the overflow: 260 wraps silently to 4.

$ dotnet run
b1 + b2 = 300
(byte)(b1 + b2) = 44
250 += 10 -> 4
after ++ -> 5
short *= 2 -> 20 (Int16)

Conversions of method arguments

Arguments are implicitly converted to the types of the parameters. When several overloads are applicable, the compiler chooses the one with the better conversion; a conversion to a narrower type is better than one to a wider type.

Program.cs
int i = 42;
byte b = 10;
float f = 1.5f;

Printer.Print(i);
Printer.Print(b);
Printer.Print(f);
Printer.Print(10L);
Printer.Print((long)3.99);

static class Printer
{
    public static void Print(long value) => Console.WriteLine($"Print(long): {value}");
    public static void Print(double value) => Console.WriteLine($"Print(double): {value}");
}

The Print method has a long and a double overload.

Printer.Print(i);
Printer.Print(b);
Printer.Print(f);

int and byte convert implicitly to both long and double; the long overload wins because long converts implicitly to double, but not the other way. A float does not convert implicitly to long, so only the double overload applies.

Printer.Print((long)3.99);

A cast selects the overload explicitly. Local functions cannot be overloaded, so the methods are in a static class.

$ dotnet run
Print(long): 42
Print(long): 10
Print(double): 1.5
Print(long): 10
Print(long): 3

Conversions in expressions and initializers

The conditional operator and implicitly typed arrays need a single type for all their values; the compiler picks the best common type. Collection expressions and array initializers with an explicit type convert every element to the element type.

Program.cs
var x = true ? 5 : 5.5;
Console.WriteLine($"true ? 5 : 5.5 -> {x} ({x.GetType().Name})");

var arr = new[] { 1, 2, 3.5 };
Console.WriteLine($"new[] {{ 1, 2, 3.5 }} -> {arr.GetType().Name}");

double[] doubles = [1, 2, 3.5];
Console.WriteLine(string.Join(", ", doubles));

long[] longs = [1, 2, int.MaxValue];
Console.WriteLine(string.Join(", ", longs));

object[] objects = [1, "hello", 3.14];
Console.WriteLine(string.Join(", ", objects.Select(o => o.GetType().Name)));

We mix integer and floating-point values in several constructs.

var x = true ? 5 : 5.5;

The type of the conditional expression is double, so even the chosen value 5 becomes a double.

var arr = new[] { 1, 2, 3.5 };

The best common type of the elements is double, so the array is a double[].

object[] objects = [1, "hello", 3.14];

In an object[], each value type element is boxed and keeps its original type.

$ dotnet run
true ? 5 : 5.5 -> 5 (Double)
new[] { 1, 2, 3.5 } -> Double[]
1, 2, 3.5
1, 2, 2147483647
Int32, String, Double

Boxing and unboxing

Boxing is the implicit conversion of a value type to object or to an interface it implements. The value is copied into a new object on the heap. Unboxing is the explicit conversion back; it succeeds only if the object contains exactly the target type.

Program.cs
int num = 42;
object boxed = num;
int unboxed = (int)boxed;

Console.WriteLine($"Boxed type: {boxed.GetType().Name}, value: {boxed}");
Console.WriteLine($"Unboxed: {unboxed}");

num = 100;
Console.WriteLine($"After changing num, boxed is still {boxed}");

try
{
    long wrong = (long)boxed;
    Console.WriteLine(wrong);
}
catch (InvalidCastException e)
{
    Console.WriteLine($"(long)boxed: {e.Message}");
}

long right = (int)boxed;
Console.WriteLine($"(long)(int)boxed: {right}");

IComparable comparable = 5;
Console.WriteLine($"Interface boxing: {comparable.CompareTo(3)}");

We box an integer and unbox it.

num = 100;
Console.WriteLine($"After changing num, boxed is still {boxed}");

The box holds a copy, so changes of the original variable do not affect it.

long wrong = (long)boxed;

Although int converts implicitly to long, a boxed int cannot be unboxed as long; the cast throws an InvalidCastException.

long right = (int)boxed;

We first unbox to the exact type and then let the implicit numeric conversion do the rest.

$ dotnet run
Boxed type: Int32, value: 42
Unboxed: 42
After changing num, boxed is still 42
(long)boxed: Unable to cast object of type 'System.Int32' to type 'System.Int64'.
(long)(int)boxed: 42
Interface boxing: 1

Reference conversions

A reference to a derived class converts implicitly to its base class or to an implemented interface; this is an upcast. The opposite direction, a downcast, requires a cast and is checked at run time. The as operator and the is pattern test the type without throwing.

Program.cs
Animal a = new Dog("Rex");
Console.WriteLine($"Upcast: {a.Name} is {a.GetType().Name}");

Dog d = (Dog)a;
Console.WriteLine($"Downcast: {d.Bark()}");

Animal c = new Cat("Tom");

try
{
    Dog wrong = (Dog)c;
}
catch (InvalidCastException e)
{
    Console.WriteLine(e.Message);
}

Dog? maybe = c as Dog;
Console.WriteLine($"as: {maybe?.Name ?? "null"}");

if (a is Dog dog)
{
    Console.WriteLine($"is pattern: {dog.Bark()}");
}

record Animal(string Name);
record Dog(string Name) : Animal(Name)
{
    public string Bark() => $"{Name} says woof";
}
record Cat(string Name) : Animal(Name);

We convert between an Animal record and its derived records.

Animal a = new Dog("Rex");

The upcast is implicit. The object stays a Dog, as GetType shows; only the static type of the variable is Animal.

Dog wrong = (Dog)c;

Casting a Cat to Dog throws an InvalidCastException.

Dog? maybe = c as Dog;

The as operator returns null when the conversion fails.

if (a is Dog dog)

The type pattern tests the type and assigns the converted reference to a new variable in one step. It is the preferred way in modern C#.

$ dotnet run
Upcast: Rex is Dog
Downcast: Rex says woof
Unable to cast object of type 'Cat' to type 'Dog'.
as: null
is pattern: Rex says woof

User-defined conversions

A type can define its own conversions with the implicit operator and explicit operator declarations. A conversion should be implicit only if it never throws and never loses information.

Program.cs
Celsius c = new(25);
Fahrenheit f = c;
Console.WriteLine($"{c} = {f}");

Celsius back = (Celsius)new Fahrenheit(212);
Console.WriteLine($"212 F = {back}");

double raw = (double)c;
Console.WriteLine($"Raw value: {raw}");

readonly record struct Celsius(double Degrees)
{
    public static implicit operator Fahrenheit(Celsius c) => new(c.Degrees * 9 / 5 + 32);
    public static explicit operator Celsius(Fahrenheit f) => new((f.Degrees - 32) * 5 / 9);
    public static explicit operator double(Celsius c) => c.Degrees;

    public override string ToString() => $"{Degrees} C";
}

readonly record struct Fahrenheit(double Degrees)
{
    public override string ToString() => $"{Degrees} F";
}

We define conversions between Celsius and Fahrenheit temperatures.

public static implicit operator Fahrenheit(Celsius c) => new(c.Degrees * 9 / 5 + 32);
public static explicit operator Celsius(Fahrenheit f) => new((f.Degrees - 32) * 5 / 9);

Both conversions are defined in the Celsius type; a conversion operator must be declared in the source or the target type. We make the conversion to Fahrenheit implicit and the other one explicit for demonstration.

Fahrenheit f = c;

The implicit conversion is applied without a cast.

double raw = (double)c;

The explicit conversion to double extracts the raw number.

$ dotnet run
25 C = 77 F
212 F = 100 C
Raw value: 25

Converting strings

There is no implicit or explicit conversion between strings and numbers. Strings are parsed with the Parse and TryParse methods of the target types, or with the Convert class, and values are formatted with ToString.

Program.cs
using System.Globalization;

string valid = "123";
string invalid = "abc";

int n = int.Parse(valid);
Console.WriteLine($"Parsed: {n}");

try
{
    int.Parse(invalid);
}
catch (FormatException e)
{
    Console.WriteLine($"Parse error: {e.Message}");
}

if (!int.TryParse(invalid, out int result))
{
    Console.WriteLine($"TryParse failed, result is {result}");
}

double d = double.Parse("3.14", CultureInfo.InvariantCulture);
Console.WriteLine(d.ToString(CultureInfo.InvariantCulture));

string s = 255.ToString("X");
Console.WriteLine($"255 as hex: {s}");
Console.WriteLine($"Convert.ToInt32(\"FF\", 16): {Convert.ToInt32("FF", 16)}");

We parse valid and invalid strings and format a number.

int.Parse(invalid);

Parse throws a FormatException for invalid input.

if (!int.TryParse(invalid, out int result))

TryParse returns false instead and sets the out variable to 0. It is the right choice for user input.

double d = double.Parse("3.14", CultureInfo.InvariantCulture);

Floating-point parsing depends on the culture; we use the invariant culture so that the dot is always the decimal separator. The Convert article covers these conversions in detail.

$ dotnet run
Parsed: 123
Parse error: The input string 'abc' was not in a correct format.
TryParse failed, result is 0
3.14
255 as hex: FF
Convert.ToInt32("FF", 16): 255

Source

Built-in numeric conversions - C# reference

C# language specification - Conversions

In this article we have worked with type conversions in C#. See also the Convert, floating-point types, and nullable types tutorials.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.