Type Conversion and Casting
Vaibhav • September 11, 2025
In programming, data often needs to change form. A number entered by a user might arrive as text, but your program needs it as an integer. A calculation might produce a decimal, but you want to store it as a whole number. These transformations are called type conversions and casting. In C#, they allow you to move between compatible types safely and intentionally. This article introduces both concepts, explains the difference between implicit and explicit conversions, and shows how to convert strings to numbers using built-in methods - all using concepts we've already covered.
Why convert types?
Every variable in C# has a type. Sometimes, you need to change that type to match the context. For example, if
you read user input using Console.ReadLine
, the result is a string
. But if the user typed a number, you’ll want to convert that string to an
int
so you can perform calculations.
string input = "42";
int number = Convert.ToInt32(input);
Here, the string "42"
is converted to the integer 42
. This is a common pattern in real-world programs - especially those that
interact with users or external data.
Type conversion is about changing the representation of data. It can happen automatically (implicit) or require a manual step (explicit). C# enforces strong typing, so conversions must be clear and safe.
Implicit conversions - automatic and safe
An implicit conversion happens automatically when C# knows it’s safe. For example, converting a smaller numeric type to a larger one doesn’t lose data, so the compiler allows it without extra syntax.
int small = 100;
long big = small; // implicit conversion from int to long
In this example, small
is an int
, and big
is a long
. Since long
can hold larger values than int
, the
conversion is safe and automatic.
You don’t need to write any special code - the compiler handles it for you. This makes your code cleaner and avoids unnecessary clutter.
Explicit conversions - manual and careful
An explicit conversion (also called casting) is required when there’s a risk of data loss. For
example, converting a double
(which can hold decimals) to an int
(which cannot) requires a cast.
double price = 19.99;
int rounded = (int)price; // explicit cast
Here, price
holds the value 19.99
. When cast
to int
, the decimal part is removed, and rounded
becomes 19
. This is a deliberate action
- you’re telling the compiler, “I know this might lose data, and I accept that.”
Casting doesn’t round - it truncates. That means 19.99
becomes 19
, not 20
. This behavior is consistent and
predictable, but it can surprise
beginners.
Converting strings to numbers
One of the most common conversions in beginner programs is turning a string into a number. This happens when you
read input using Console.ReadLine
, which always returns a string - even if the
user typed a number.
string input = "25";
int age = Convert.ToInt32(input);
The method Convert.ToInt32
takes a string and returns an integer. If the string
contains a valid number, the conversion succeeds. If not, the program will crash - we’ll learn how to handle
that later.
Using int.Parse
Another way to convert a string to an integer is using int.Parse
. It works
similarly to Convert.ToInt32
, but is slightly stricter.
string input = "42";
int number = int.Parse(input);
This method assumes the string is a valid number. If it’s not - for example, if the string is "hello"
- the program will crash. Later, we’ll learn safer methods that check
before converting.
Use Convert.ToInt32
when you expect the input might be empty
or null. Use int.Parse
when you’re confident the input is a valid number.
Casting pitfalls - when things go wrong
Casting can be powerful, but it’s also risky. If you cast a value incorrectly, you might lose data or cause
unexpected behavior. One common mistake is casting a double
to an int
without realizing it removes the decimal part.
double value = 3.99;
int result = (int)value;
Console.WriteLine(result); // Output: 3
The output is 3
, not 4
. This is because
casting truncates - it doesn’t round. If you want rounding, you’ll need a different method (covered later).
Another pitfall is casting between incompatible types. For example, you cannot cast a string
directly to an int
- you must use a
conversion method.
// Incorrect
string text = "100";
int number = (int)text; // ❌ Error
// Correct
int number = Convert.ToInt32(text); // ✅
The first example causes a compile-time error. The second uses a proper conversion method and works as expected.
C# prevents unsafe casts at compile time. If you try to cast between incompatible types, the compiler will stop you - unless you use special techniques (covered in advanced chapters).
Converting between numeric types
You can convert between numeric types - like int
, long
, float
, and double
. Some conversions are implicit, others require casting.
int whole = 10;
double precise = whole; // implicit conversion
double value = 9.75;
int rounded = (int)value; // explicit cast
The first line converts int
to double
automatically. The second line casts double
to int
, removing the decimal part.
String interpolation with conversions
You can use converted values inside interpolated strings to build dynamic messages. This helps you display results clearly and professionally.
string input = "30";
int age = Convert.ToInt32(input);
string message = $"You are {age} years old.";
Console.WriteLine(message);
The string input
is converted to an integer, then used inside a message. This
pattern is common in user-facing applications.
Common mistakes and how to avoid them
Beginners often confuse casting with conversion. For example, trying to cast a string
to an int
using parentheses will fail.
Always use Convert.ToInt32
or int.Parse
for
strings.
Another mistake is assuming casting rounds numbers. It doesn’t - it truncates. If you need rounding, you’ll learn how to do that in later chapters.
// Incorrect
double value = 4.9;
int result = (int)value; // ❌ result is 4, not 5
// Correct (later)
int result = Math.Round(value); // ✅ rounds to 5
For now, remember that casting removes the decimal part - it doesn’t round.
Use casting only when you’re sure it’s safe. Prefer conversion methods for user input and string data. Always test your conversions to avoid surprises.
Conversions in algorithms
In Chapter 1, we introduced algorithms as step-by-step instructions. Type conversion often plays a role in these steps - especially when working with input. For example, a program that calculates age in days might start with a string input, convert it to an integer, and then perform a calculation.
string input = "25";
int age = Convert.ToInt32(input);
int ageInDays = age * 365;
Console.WriteLine($"You are approximately {ageInDays} days old.");
This simple algorithm uses conversion to turn user input into a usable number. Without conversion, the calculation wouldn’t be possible.
Summary
Type conversion and casting are essential tools in C#. They allow you to change the form of data - from strings
to numbers, from decimals to integers, and between numeric types. Implicit conversions happen automatically when
safe. Explicit conversions (casting) require manual syntax and care. You learned how to use Convert.ToInt32
and int.Parse
to turn strings
into integers, and how casting affects decimal values.
These skills help you write flexible, user-friendly programs. Whether you’re reading input, performing calculations, or formatting output, conversions make your code work smoothly. As you continue learning, you’ll discover more advanced techniques - but these fundamentals will always be part of your toolkit.