Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Types and Literals

Type conversions

Reference for C# type conversions: implicit and explicit casts, numeric widening and narrowing, as and is, Parse and TryParse, Convert, and user-defined conversions.

C# is statically typed, so every value has a type, and moving a value into a variable of another type needs a conversion. The compiler distinguishes conversions that cannot lose information and are applied automatically (implicit) from those that may lose data or fail and must be requested with a cast (explicit).

Beyond casts there are three more tools: the as and is operators for reference types, Parse/TryParse for text, and the Convert class for general-purpose conversion between base types.

C#
int small = 42;
long wide = small;          // implicit: always safe
int back = (int)wide;       // explicit: may lose data

Try it

C# Numeric conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# References, parsing and user-defined conversions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
Target t = source;              // implicit conversion
Target t = (Target)source;      // explicit cast
Target? t = source as Target;   // null if not convertible (reference/nullable types)
bool ok = source is Target t2;  // test and convert
bool ok = int.TryParse(text, out int value);
Kind When it happens
Implicit numeric Widening without loss of range: byte to short/int/long/double, int to long/double/decimal, float to double, char to ushort and up. long to float/double is implicit but can lose digits.
Explicit numeric Narrowing, signed/unsigned changes, double to decimal or to any integer type.
Reference Implicit to a base class or implemented interface; explicit down the hierarchy, checked at run time.
Boxing / unboxing Value type to object or interface and back. See Boxing and unboxing.
User-defined implicit and explicit operators; see implicit and explicit.
Constant expression A constant that fits the range converts implicitly: byte b = 200;.

Errors. An explicit reference cast that fails throws InvalidCastException; a checked numeric narrowing throws OverflowException; Parse throws FormatException for bad text, OverflowException for out-of-range values and ArgumentNullException for null. TryParse never throws and sets the out parameter to the default.

Usage notes

  • Unchecked by default. Numeric casts silently wrap or truncate unless the code is in a checked context. See Integer overflow.
  • Casting a floating-point value to an integer truncates; Math.Round, Convert.ToInt32 (which rounds to even) or Math.Floor are alternatives. Casting NaN or out-of-range values gives an unspecified result; check first.
  • as vs cast. as returns null instead of throwing but works only for reference and nullable targets; prefer pattern matching (is T t) so you get a usable variable.
  • Unboxing must name the exact type. (int)obj fails for a boxed long even though long to int casts normally. Unbox to long first, then cast.
  • Parse for input. Use TryParse for user input, and pass CultureInfo.InvariantCulture when the text format is fixed. Our runner has only the invariant culture; examples with other cultures are read-only.
  • Convert quirks. Convert.ToInt32 of a null string returns 0, while int.Parse(null) throws ArgumentNullException. Convert.ToInt32(double) rounds to even instead of truncating like a cast.
  • Define conversions sparingly. Make a conversion implicit only if it never loses information and never throws.
  • Generic math. T.CreateChecked, CreateSaturating and CreateTruncating convert between numeric types generically with explicit overflow policies.