Type Conversion: The Shape Shifter

Type Conversion: The Shape Shifter in C#: Converting a value is pouring liquid from one jug into another.

The Analogy: Pouring Between Jugs

Converting a value is pouring liquid from one jug into another. Pouring a small jug into a large one always works and nothing is lost — the compiler lets you do it without asking, which is called an implicit conversion. Pouring a large jug into a small one might spill, so C# makes you say out loud that you accept the risk: that is a cast, and the spill is real.

There is a third case that is not pouring at all. Turning the word "42" into the number 42 is translation, not transfer, and it can fail outright because "forty-two" is not a number in any jug. That is parsing, and it is where almost every real-world conversion bug lives, because parsing is what you do to data that came from a user, a file or an HTTP request.

Keeping those three apart — widen, cast, parse — makes the whole topic small.


Syntax or Core Structure

using System;

class Program
{
    static void Main()
    {
        int count = 7;
        double widened = count;          // implicit: int fits in double
        int narrowed = (int)3.99;        // explicit cast: truncates

        Console.WriteLine($"widened {widened}, narrowed {narrowed}");
        Console.WriteLine($"(int)-3.9 = {(int)-3.9}");
        Console.WriteLine($"Convert.ToInt32(2.5) = {Convert.ToInt32(2.5)}");
        Console.WriteLine($"Convert.ToInt32(3.5) = {Convert.ToInt32(3.5)}");
        Console.WriteLine($"Math.Round(2.5) = {Math.Round(2.5)}");
        Console.WriteLine($"(byte)300 = {(byte)300}");

        int parsed = int.Parse("42");
        bool ok = int.TryParse("x1", out int failed);
        Console.WriteLine($"parsed {parsed}, ok {ok}, failed {failed}");
    }
}

Output:

widened 7, narrowed 3
(int)-3.9 = -3
Convert.ToInt32(2.5) = 2
Convert.ToInt32(3.5) = 4
Math.Round(2.5) = 2
(byte)300 = 44
parsed 42, ok False, failed 0

Every line of that output is a lesson.

A cast to int truncates towards zero. 3.99 becomes 3 and -3.9 becomes -3, not -4. If you wanted the nearest whole number you needed Math.Round, and if you wanted the floor you needed Math.Floor.

Convert.ToInt32 and Math.Round use banker's rounding. 2.5 goes to 2 and 3.5 goes to 4: midpoints round to the even neighbour, which keeps long sums unbiased but astonishes everyone the first time. Math.Round(2.5, MidpointRounding.AwayFromZero) gives the 3 most people expect.

(byte)300 is 44, silently. 300 minus 256 is 44; the cast keeps the low byte and discards the rest without a word. checked((byte)300) throws instead.

TryParse returns false and writes 0 into its out parameter rather than throwing. That is what makes it the right tool for input you did not write yourself.


Technical Depth: The Four Mechanisms

MechanismWritten asFails byUse for
Implicitdouble d = anInt;cannot failwidening, upcasting
Explicit cast(int)aDoublewraps, truncates, or InvalidCastExceptionnarrowing you have checked
Convert.*Convert.ToInt32(x)FormatException, OverflowExceptionobject of unknown numeric type
Parse / TryParseint.TryParse(s, out n)returns false / throwstext from outside the program

Which widenings are implicit

int    i = 42;
long   l = i;      // ok
float  f = l;      // ok - loses precision but not magnitude
double d = f;      // ok
decimal m = i;     // ok - int to decimal is implicit

double back = m;   // ERROR - decimal to double needs a cast
decimal m2 = d;    // ERROR - double to decimal needs a cast
int narrow = l;    // ERROR - long to int needs a cast
char c = 'A';
int code = c;      // ok - 65

The chain byte → short → int → long → float → double is implicit throughout, and every integer type converts implicitly to decimal. The one pair that refuses both directions is decimal and the binary floating-point types, because neither can represent the other faithfully — decimal has more digits, double has more range.

Parse, TryParse, Convert

int a = int.Parse("42");             // 42
int b = int.Parse("4.2");            // FormatException
int c = int.Parse(null);             // ArgumentNullException
int d = int.Parse("99999999999");    // OverflowException

int e = Convert.ToInt32(null);       // 0 - no exception
int f = Convert.ToInt32("42");       // 42

if (int.TryParse(input, out int g))  // never throws
    Console.WriteLine(g);

Parse is for text you are certain about — a literal in a test, a value you just wrote yourself. TryParse is for everything else. Convert.ToInt32(null) returning 0 looks convenient and is a trap: a missing field and a genuine zero become indistinguishable.

Culture decides what a decimal point is

using System.Globalization;

double.Parse("3.14");                                   // depends on the machine
double.Parse("3.14", CultureInfo.InvariantCulture);     // always 3.14
(1234.5).ToString("N2", CultureInfo.InvariantCulture);  // "1,234.50"

In German or French locales the comma is the decimal separator, so "3.14" parses as 314 on a machine configured that way — a bug that passes every test on the developer's laptop. The rule: InvariantCulture for machine-readable data (files, JSON, protocols) and CurrentCulture for text a human will read.

Reference conversions and boxing

object o = 42;                 // boxing: the int is copied onto the heap
int back = (int)o;             // unboxing
double wrong = (double)o;      // InvalidCastException - it is a boxed int

object s = "hello";
string t = s as string;        // "hello"
int? n = s as int?;            // null, no exception
if (s is string str)           // preferred: test and bind in one step
    Console.WriteLine(str.Length);

A cast on reference types is a run-time check, not a transformation: it either succeeds or throws InvalidCastException. as yields null instead of throwing, and the is pattern does the test and the assignment together, which is the modern idiom.

Boxing wraps a value type in a heap object so it can be treated as object. It allocates, and in a tight loop that allocation is the whole cost of the loop. Generics exist largely to avoid it: List<int> stores unboxed ints, while the ancient ArrayList boxed every one.


Real World Example: A Tolerant Import

Real input is dirty. A row may have the wrong number of fields, a quantity that is not a number, or a blank price. The job is to accept what is valid, report what is not, and never crash.

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
        string[] rows =
        {
            "widget;12;3.50",
            "gizmo;abc;1.00",
            "sprocket;5;2.25",
            "cog;40;",
        };

        decimal total = 0m;
        int accepted = 0, rejected = 0;

        foreach (string row in rows)
        {
            string[] parts = row.Split(';');

            if (parts.Length != 3
                || !int.TryParse(parts[1], NumberStyles.Integer,
                                 CultureInfo.InvariantCulture, out int qty)
                || !decimal.TryParse(parts[2], NumberStyles.Number,
                                     CultureInfo.InvariantCulture, out decimal price))
            {
                Console.WriteLine($"rejected: {row}");
                rejected++;
                continue;
            }

            decimal value = qty * price;
            total += value;
            accepted++;

            Console.WriteLine($"{parts[0],-10}{qty,4}{price,8:F2}{value,9:F2}");
        }

        Console.WriteLine($"accepted {accepted}, rejected {rejected}, total {total:F2}");
    }
}

Output:

widget      12    3.50    42.00
rejected: gizmo;abc;1.00
sprocket     5    2.25    11.25
rejected: cog;40;
accepted 2, rejected 2, total 53.25

12 × 3.50 is 42.00 and 5 × 2.25 is 11.25, so the total is 53.25. The gizmo row fails on "abc" and the cog row fails on an empty price string, which TryParse treats as a failure rather than as zero.

The three checks are chained with || on purpose. || short-circuits, so if the field count is wrong the parses never run, and out int qty is declared inline in the condition yet is still in scope for the rest of the loop body. That is the standard shape for validate-then-use in modern C#.

CultureInfo.InvariantCulture is not optional here. This is a data file, so 3.50 must mean three and a half on every machine that ever runs the importer.

NumberStyles.Integer refuses "3.50" as a quantity — it permits a sign and surrounding whitespace but no decimal point, so a fractional count is rejected rather than silently truncated. Being specific about the accepted shape is half of validation.

Nothing here throws. Swap the two TryParse calls for int.Parse and decimal.Parse and the program dies on row two with a FormatException, having already printed one row and having no total at all.


Common Mistakes

  1. Expecting (int) to round. (int)4.99 is 4 and (int)-4.99 is -4. The cast throws away the fraction; Math.Round, Math.Floor and Math.Ceiling are three different answers and you must pick one.
  2. Being surprised by banker's rounding. Math.Round(0.5) is 0 and Math.Round(1.5) is 2. When a business rule says "half rounds up", pass MidpointRounding.AwayFromZero explicitly.
  3. Calling Parse on user input. One malformed character and the process dies with a FormatException. TryParse at every boundary — form fields, query strings, file rows, environment variables.
  4. Parsing numbers without a culture. double.Parse("3.14") returns 314 on a machine whose locale uses a comma. Always pass CultureInfo.InvariantCulture for data, and never rely on the default.
  5. Narrowing without checking the range. (byte)300 is 44 and (int)long.MaxValue is -1. Compare against byte.MaxValue first, or wrap the cast in checked.
  6. Using + to convert a number to text and back. "5" + 3 is the string "53", not 8, because the int is converted to string rather than the other way round. Parse the string first if you meant arithmetic.
  7. Unboxing to the wrong type. object o = 42; double d = (double)o; throws InvalidCastException even though int widens to double — the boxed type must match exactly. Write (double)(int)o.
  8. Trusting Convert.ToInt32(null). It returns 0 with no complaint, so a missing value becomes a legitimate-looking zero. Check for null yourself, or use TryParse where false tells you plainly that nothing was there.

Best Practices

  • Validate at the edges and convert once. Parse incoming text into real types at the boundary of your program, and let everything inside work with int, decimal and DateTime rather than strings.
  • Default to TryParse and reserve Parse for literals you control. The out variable declared inline keeps the code as short as the throwing version.
  • Pass CultureInfo.InvariantCulture for anything machine-readable and CultureInfo.CurrentCulture only when formatting for a person.
  • Name the rounding rule you want. Math.Round(x, 2, MidpointRounding.AwayFromZero) documents a decision that Math.Round(x, 2) leaves for a future reader to discover.
  • Prefer is Type value to a bare cast when the type is not certain. It handles the failing case without an exception and binds the result in the same line.
  • Restrict what TryParse will accept with NumberStyles. Allowing currency symbols or thousands separators should be a decision, not an accident.
  • Keep decimal and double in separate lanes. If a program needs both, convert deliberately at one named place and comment why.
  • Avoid boxing in hot paths: use generic collections and generic methods rather than object parameters, and watch for string.Format and interpolation in loops that run millions of times.

Practice Exercises

  1. Print (int)x, Math.Round(x), Math.Floor(x) and Math.Ceiling(x) for x in { 2.4, 2.5, 2.6, -2.5 } as a four-column table, then write one sentence for each column describing its rule.
  2. Write a method static int SafeToInt(string? text, int fallback) that returns the parsed value, or fallback when the text is null, blank or not a number. Test it with "7", "", null, "7.5" and "99999999999".
  3. Extend the tolerant import with a fourth field holding a date in yyyy-MM-dd form, parsed with DateTime.TryParseExact and InvariantCulture. Reject rows whose date is malformed and keep the accepted/rejected counts correct.
  4. Demonstrate boxing: put 1, 2.5 and "three" into an object[], then loop over it and use is patterns to print each element's type and value without a single InvalidCastException.