Learn C# in Y Minutes
C# 14 · .NET 10

03. Type Conversion

Because every variable has a fixed type, you often need to turn a value of one type into another: an int into a double, or the text "42" into the number 42. C# makes safe conversions easy and risky ones explicit.

Implicit conversion

When the target type can hold every possible value of the source type, C# converts implicitly, with no extra syntax. A byte always fits in an int, so nothing can be lost.

app/03-type-conversion/Implicit.cs
byte small = 200;
int medium = small;
long large = medium;
double real = large;

Console.WriteLine($"{small} -> {medium} -> {large} -> {real}");
200 -> 200 -> 200 -> 200

Explicit conversion (casting)

When data might be lost, the compiler refuses until you cast: put the target type in parentheses. The cast says "I know, do it anyway". Decimals are cut off (not rounded), and numbers too big for the target wrap around.

app/03-type-conversion/Explicit.cs
double price = 9.99;
int whole = (int)price;
Console.WriteLine($"(int){price} = {whole}");

int big = 300;
byte squeezed = (byte)big;
Console.WriteLine($"(byte){big} = {squeezed}");
(int)9.99 = 9
(byte)300 = 44

Parse and Convert

Casting only works between compatible types. A string is not a number, so you cannot cast it. Instead, Parse reads text into a number, and the Convert class converts between many types. Note that Convert.ToInt32 rounds, unlike a cast.

app/03-type-conversion/ConvertParse.cs
string ageText = "42";
string priceText = "19.95";

int age = int.Parse(ageText);
decimal price = decimal.Parse(priceText);
bool isActive = Convert.ToBoolean("true");
int rounded = Convert.ToInt32(7.6);

Console.WriteLine($"{age + 1} {price * 2} {isActive} {rounded}");
43 39.90 True 8

If the text is not a valid number, Parse throws a FormatException and the program crashes unless you catch it. Exceptions get their own lesson later, for now just see what happens:

app/03-type-conversion/BadInput.cs
try
{
    int quantity = int.Parse("ten");
    Console.WriteLine(quantity);
}
catch (FormatException)
{
    Console.WriteLine("\"ten\" is not a number");
}
"ten" is not a number

TryParse: the safe way

Input from users is often wrong. TryParse never throws. It returns true or false, and hands the parsed number back through an out variable. This is the pattern to use for anything you do not control.

app/03-type-conversion/TryParse.cs
string[] inputs = ["25", "abc", "-3", ""];

foreach (var input in inputs)
{
    if (int.TryParse(input, out int number))
        Console.WriteLine($"\"{input}\" -> {number}");
    else
        Console.WriteLine($"\"{input}\" -> invalid");
}
"25" -> 25
"abc" -> invalid
"-3" -> -3
"" -> invalid

Numbers to text

Every value has a ToString() method. Pass a format string to control how it looks: N2 adds thousand separators and 2 decimals, P1 shows a percentage, D3 pads with zeros. The same codes work inside interpolated strings after a colon.

app/03-type-conversion/ToStringFormat.cs
int count = 7;
double ratio = 0.8567;
decimal total = 1234.5m;

string text = count.ToString();
Console.WriteLine(text + " items");
Console.WriteLine(ratio.ToString("P1"));
Console.WriteLine(total.ToString("N2"));
Console.WriteLine($"{count:D3} | {ratio:F2}");
7 items
85.7 %
1,234.50
007 | 0.86

Number formats follow the computer's culture. On a machine set to Indonesian, 1234.5m.ToString("N2") prints 1.234,50. Servers usually format data for machines, so APIs return raw numbers in JSON and let the client format them.

ASP.NET Core converts for you. A route like /products/42 arrives as text, and model binding turns it into an int. A route constraint such as {id:int} uses the TryParse idea: non-numbers never reach your code.

Program.cs
app.MapGet("/products/{id:int}", (int id) => $"Product {id}");

Quick quiz