TExcelTAD
Home › C# › C# Type Casting

C# Type Casting

Type casting means converting a value from one type to another. C# distinguishes conversions that can never lose information (done automatically) from those that might (which you must ask for explicitly).

Implicit conversions

When the target type can hold every possible value of the source type, the compiler converts automatically. This is called widening:

byte → short → int → long → float → double

csharp · try it yourself
using System;

int apples = 12;
long bigApples = apples;     // int -> long
double precise = apples;     // int -> double

Console.WriteLine(bigApples);
Console.WriteLine(precise / 5);
12
2.4

Explicit conversions (casts)

Going the other way — narrowing — could lose data, so C# requires a cast: the target type in parentheses before the value.

csharp · try it yourself
using System;

double price = 9.99;
int whole = (int)price;          // fractional part is dropped, not rounded
Console.WriteLine(whole);

int big = 300;
byte small = (byte)big;          // 300 does not fit in a byte: it wraps around
Console.WriteLine(small);

char letter = (char)65;
Console.WriteLine(letter);
9
44
A

Casting a double to an integer truncates toward zero, and casting an out-of-range integer wraps around silently (300 − 256 = 44). If you want an error instead, wrap the code in a checked block — it throws an OverflowException.

Without a cast, a narrowing assignment does not compile:

csharp
double ratio = 0.75;
int value = ratio; // error CS0266: Cannot implicitly convert type 'double' to 'int'

The Convert class

System.Convert provides methods for converting between the basic types. Unlike a cast, Convert.ToInt32 rounds a double (to the nearest even number when exactly halfway) and throws on overflow.

csharp · try it yourself
using System;

Console.WriteLine(Convert.ToInt32(9.99));
Console.WriteLine(Convert.ToInt32(2.5));
Console.WriteLine(Convert.ToInt32(3.5));
Console.WriteLine(Convert.ToDouble("12.5"));
Console.WriteLine(Convert.ToBoolean("true"));
Console.WriteLine(Convert.ToString(123) + "!");
10
2
4
12.5
True
123!

Parsing strings: Parse and TryParse

Text — from a file, a form or the console — must be parsed into numbers. Every numeric type has Parse, which throws a FormatException on bad input, and TryParse, which returns false instead.

csharp · try it yourself
using System;

int a = int.Parse("250");
Console.WriteLine(a + 1);

string[] inputs = { "42", "abc", "7.5", "-3" };
foreach (string input in inputs)
{
    if (int.TryParse(input, out int number))
        Console.WriteLine(
quot;'{input}' -> {number}"); else Console.WriteLine(
quot;'{input}' is not a whole number"); }
251
'42' -> 42
'abc' is not a whole number
'7.5' is not a whole number
'-3' -> -3

Tip: Prefer TryParse for anything a user typed. Exceptions are for unexpected situations, and bad input is entirely expected.

Converting to strings

Every value has a ToString() method. Numeric types accept a format string:

Call Result
42.ToString() 42
3.14159.ToString("F2") 3.14
1234567.ToString("N0") 1,234,567
0.25.ToString("P0") 25 % (invariant culture; 25% in en-US)
255.ToString("X") FF

Note: Formatting and parsing of decimals follow the computer's culture settings (some countries write 12,5). For machine-readable data, pass CultureInfo.InvariantCulture from System.Globalization.

Test yourself

What does (int)7.9 evaluate to?

  1. 8
  2. 7
  3. 7.9
  4. A compile error

Which method converts a string to an int without throwing on bad input?

  1. int.Parse
  2. Convert.ToInt32
  3. int.TryParse
  4. (int)

Which conversion happens implicitly?

  1. double to int
  2. long to int
  3. int to double
  4. double to float