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.
int small = 42; long wide = small; // implicit: always safe int back = (int)wide; // explicit: may lose data
Try it
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.
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
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
checkedcontext. See Integer overflow. - Casting a floating-point value to an integer truncates;
Math.Round,Convert.ToInt32(which rounds to even) orMath.Floorare alternatives. Casting NaN or out-of-range values gives an unspecified result; check first. asvs cast.asreturnsnullinstead 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)objfails for a boxedlongeven thoughlongtointcasts normally. Unbox tolongfirst, then cast. - Parse for input. Use
TryParsefor user input, and passCultureInfo.InvariantCulturewhen the text format is fixed. Our runner has only the invariant culture; examples with other cultures are read-only. Convertquirks.Convert.ToInt32of anullstring returns0, whileint.Parse(null)throwsArgumentNullException.Convert.ToInt32(double)rounds to even instead of truncating like a cast.- Define conversions sparingly. Make a conversion
implicitonly if it never loses information and never throws. - Generic math.
T.CreateChecked,CreateSaturatingandCreateTruncatingconvert between numeric types generically with explicit overflow policies.