Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 182 ยท Variables and Types

Type Conversion and Casting

Learn C# type conversion - implicit and explicit casts, truncation and overflow, the Convert class, Parse and TryParse, is and as, user-defined conversions and BitConverter.

C# is a statically typed language: every value has a type, and the compiler checks that you use it correctly. But real programs constantly need to change one type into another. A user types "42" and you need the number 42. A calculation produces a double and you need a whole number of items. A Dog is stored in a variable typed Animal and you need the dog back.

C# splits conversions into groups based on one question: can this conversion lose information or fail? If it can't, the compiler does it for you silently (an implicit conversion). If it can, you must say so in the code with a cast, a method call or a pattern (an explicit conversion). This lesson walks through all the tools: numeric casts, the Convert class, Parse and TryParse, is and as for reference types, your own conversion operators, and BitConverter for raw bytes.

Implicit conversions: safe, automatic

An implicit conversion never loses data and never throws. The compiler inserts it whenever a value of a "smaller" type is used where a "bigger" one is expected.

C# Implicit 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.

The main implicit paths for numbers are sbyte / byte / short / int / long / float / double going from small to large, and every integer type to float, double or decimal. Notice long to float is allowed even though a float has only 24 bits of precision: it can lose digits but never overflows its range, so the language treats it as safe. Be careful with that one in practice.

decimal is deliberately stricter: no implicit conversion between decimal and float or double in either direction (see Floating-Point and decimal).

Explicit conversions: casts

When the target type is smaller or the conversion could fail, the compiler refuses until you write a cast: the target type in parentheses in front of the value.

C# Explicit casts and truncation

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.

Two important things happen here. A cast from floating-point to integer truncates toward zero; use Math.Round first when you want rounding. And a cast between integer types silently keeps only the bits that fit, so 300 becomes 44 as a byte. No exception, no warning. That is the default unchecked behavior for integer casts.

One more trap, which we don't run here because the result is unspecified: casting a double that is out of range (or NaN) to an integer type gives a value that can differ between CPUs and .NET versions. The compiler even rejects it for constants ((long)double.NaN is error CS0221). Treat out-of-range floating-point casts as a bug and check the range first.

checked: turn silent wrapping into an exception

Wrap risky casts or arithmetic in checked and an overflow throws OverflowException instead of wrapping:

C# checked 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.

You can also turn checking on for a whole project with the CheckForOverflowUnderflow compiler setting. Financial and safety-critical code often does. Integer overflow itself is the subject of Integer Types.

A cast is you telling the compiler "I know better". It does not validate anything. For data coming from outside your program (files, users, networks) use TryParse or checked, not a bare cast.

The Convert class

System.Convert converts between the base types with named methods: Convert.ToInt32, ToDouble, ToString, ToBoolean, ToDateTime, ToBase64String and many more. Compared with a cast, Convert rounds instead of truncating when it turns a floating-point number into an integer, and it throws on overflow.

Be careful: the rounding is banker's rounding (round half to even), the same default as Math.Round.

C# Convert versus a cast

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.

Convert.ToInt32(null as string) returning 0 is a common source of bugs: a missing value turns into a legitimate-looking zero. When "no value" must be detectable, use TryParse instead.

Parse and TryParse

Every numeric type has a static Parse method that turns text into a number, and a TryParse that does the same without exceptions. Prefer TryParse for any input you don't control:

  • int.Parse("12x") throws FormatException. A single bad line crashes the program unless you catch it.
  • int.TryParse("12x", out int n) returns false and sets n to 0. You decide what to do.
C# Parse versus TryParse

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.

The last four lines show the options: leading and trailing spaces are accepted by default (7), but a thousands separator is not ("1,234" gives False 0) until you pass NumberStyles.AllowThousands, and hexadecimal needs NumberStyles.HexNumber (FF is 255).

The parse methods use the current culture by default, so "3,75" may mean 3.75 in one country and 375 in another. The sandbox uses the invariant culture (a period for decimals). For data that must read the same everywhere (files, network protocols) pass CultureInfo.InvariantCulture explicitly. Reading input from the user is covered in Reading Input.

Reference conversions: is, as and casts

Conversion between reference types follows the inheritance chain. Going up (from Dog to Animal) is always safe and implicit. Going down (from Animal back to Dog) might be wrong, because the variable could hold a Cat, so it needs checking. C# gives you three ways:

  1. Cast (Dog)animal: throws InvalidCastException if the object isn't a Dog.
  2. as animal as Dog: returns null instead of throwing.
  3. is with a pattern animal is Dog dog: tests and gives you the converted variable in one step. This is usually the best choice.
C# Safe downcasting with is and as

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.

Unboxing is strict: a boxed int can be unboxed only to int (or int?), not directly to long. You must unbox to the exact type, then convert. Boxing and the value/reference split are discussed in Value Types and Reference Types. A deeper tour of is patterns is in Pattern Matching Basics.

Use as only when you want null as the "not this type" answer; a bare cast is right when a wrong type is a genuine bug that should crash loudly.

User-defined conversions

Your own types can define conversion operators. Mark a conversion implicit only when it is lossless, cannot throw and feels obvious; otherwise use explicit.

C# Custom implicit and explicit 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# looks for a conversion operator in either the source or the target type. You cannot define conversions to or from interfaces or from a base class to its own derived class (those are built in). Overusing implicit conversions makes code hard to read (which overload is called? where did this value change type?), so keep them for natural wrappers such as strongly typed ids or units.

BitConverter: numbers and raw bytes

Sometimes you need the bytes behind a value: for files, network protocols or hashing. BitConverter turns primitive values into byte arrays and back. The byte order follows the CPU, which is little-endian on x86 and ARM, so the least significant byte comes first. BitConverter.IsLittleEndian tells you.

C# Looking at the bytes of numbers

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.

BitConverter does not change the numeric meaning of a value; it exposes how it is stored. For protocols that specify a byte order (network order is big-endian) use System.Buffers.Binary.BinaryPrimitives, as the last lines show, so the code behaves identically on every machine.

Choosing the right tool

You have... You want... Use
int long, double nothing (implicit)
double int, truncated (int)x
double int, rounded Math.Round, or Convert.ToInt32
long int, must not overflow checked((int)x)
text from outside number int.TryParse
text you control number int.Parse
base-class reference derived type is Dog d or as Dog

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does (int)3.99 evaluate to?

    Casting a floating-point number to int truncates toward zero. It never rounds. Use Math.Round or Convert.ToInt32 for rounding.
  2. 2. What is the result of (byte)300 in default (unchecked) code?

    Unchecked integer casts keep only the bits that fit: 300 mod 256 is 44. Wrap the cast in checked(...) to get an OverflowException instead.
  3. 3. Which call is the best way to read a number the user typed?

    TryParse reports failure through its bool result without throwing. A cast does not compile for strings, and Parse throws FormatException on bad input.
  4. 4. Animal a = new Cat(); Dog d = a as Dog; โ€” what is d?

    as returns null when the conversion is not possible instead of throwing. The cast (Dog)a would throw InvalidCastException.
  5. 5. What does Convert.ToInt32(2.5) return?

    Convert rounds, and it uses banker's rounding (halves go to the even number), so 2.5 becomes 2 and 3.5 becomes 4.

Summary

  • Implicit conversions are safe and automatic (int to long, int to double); explicit conversions need a cast because they can lose data.
  • Casting double to an integer type truncates toward zero; casting between integer types keeps only the low bits unless you use checked.
  • Convert rounds (half to even) and throws on overflow; Convert.ToInt32(null as string) returns 0, which can hide bugs.
  • Use TryParse for outside input and Parse only when failure is a bug. Pass CultureInfo.InvariantCulture for data that must be culture independent.
  • For reference types prefer is Type name patterns; as yields null on failure, a cast throws InvalidCastException. Unboxing needs the exact boxed type.
  • Define implicit operators only for lossless, obvious conversions, otherwise explicit.
  • BitConverter shows the stored bytes (little-endian on common CPUs); use BinaryPrimitives for a fixed byte order.

Next: Nullable Value Types