Type Conversion in C#

Type conversion in C# is the process of converting a value from one data type to another. Sometimes conversion is safe and automatic, such as converting an int to a long. Other times, conversion can lose data or fail, so the programmer must explicitly request it. Type conversion is important because C# is strongly typed, and values cannot be freely mixed without rules.

You will use type conversion when reading user input, working with numbers, converting strings to numeric values, handling API data, storing values in variables, parsing files, and moving data between different layers of an application. Understanding conversion helps prevent runtime errors, data loss, and confusing compiler messages.


What Is Type Conversion in C#?

Type conversion means changing a value from one type to another type.

int number = 100;
long bigNumber = number;

Here, an int value is converted to a long. This is safe because long has a wider range than int.

Type conversion in C# is controlled by safety. Safe conversions can happen automatically, while risky conversions need explicit action.

Types of Type Conversion in C#

Conversion TypeMeaning
Implicit conversionAutomatic conversion performed by the compiler when it is safe.
Explicit conversionManual conversion requested by the programmer using a cast.
Convert classUses methods like Convert.ToInt32().
Parse methodsConvert strings to values using methods like int.Parse().
TryParse methodsSafely attempt string conversion without throwing for invalid input.

Implicit Type Conversion

Implicit conversion happens automatically when there is no risk of data loss. This usually happens when converting from a smaller numeric type to a larger numeric type.

int x = 25;
long y = x;
double z = y;

Console.WriteLine(z);

The conversion from int to long and then to double is allowed automatically because the target types can represent the source values safely in normal cases.

Explicit Type Conversion

Explicit conversion is required when conversion may lose data or fail. This is also called casting.

double price = 99.95;
int roundedPrice = (int)price;

Console.WriteLine(roundedPrice);

The output is 99. The decimal part is removed, not rounded. This is why explicit conversion should be used carefully.

Using the Convert Class

The Convert class provides methods for converting values between common types.

string input = "123";
int number = Convert.ToInt32(input);

Console.WriteLine(number);

Convert.ToInt32() can convert a valid numeric string into an integer. If the string is not valid, it can throw an exception.

Using Parse Methods

Many data types provide Parse() methods for converting strings into values.

string text = "45";
int value = int.Parse(text);

Console.WriteLine(value);

This works when the string contains a valid integer. If the string contains something invalid like "abc", Parse() throws an exception.

Using TryParse for Safe Conversion

TryParse() is safer when working with user input because it does not throw an exception for invalid text. It returns true if conversion succeeds and false if conversion fails.

string input = "150";

if (int.TryParse(input, out int number))
{
    Console.WriteLine($"Converted value: {number}");
}
else
{
    Console.WriteLine("Invalid number");
}

For user input, forms, files, and external data, TryParse() is usually better than Parse().

Convert vs Parse vs TryParse

MethodUseFailure Behavior
Convert.ToInt32()General conversion from compatible valuesMay throw exception
int.Parse()Convert valid string to integerThrows exception on invalid input
int.TryParse()Safely attempt string-to-int conversionReturns false on invalid input

String to Number Conversion

Converting strings to numbers is common when reading input from users or files.

string marksText = "88";
int marks = int.Parse(marksText);

If the input comes from a trusted source, Parse() may be acceptable. If the input comes from a user, prefer TryParse().

Number to String Conversion

Most values can be converted to strings using ToString().

int age = 21;
string ageText = age.ToString();

This is useful when displaying values, building messages, writing logs, or exporting data.

Boxing and Unboxing

Boxing converts a value type into an object. Unboxing extracts the value type back from the object.

int number = 10;
object boxed = number;      // boxing
int unboxed = (int)boxed;   // unboxing

Boxing and unboxing are important to understand because they can affect performance and type safety. Modern generic collections reduce the need for boxing in many cases.

Type Conversion with is and as

The is operator checks whether an object is compatible with a type. It can also declare a variable when the check succeeds.

object value = "Hello";

if (value is string text)
{
    Console.WriteLine(text.ToUpper());
}

The as operator attempts a reference conversion and returns null if it fails.

object item = "CSharp";
string? result = item as string;

Numeric Conversion Table

ConversionUsually Safe?Example
int to longYesImplicit
int to doubleUsually yesImplicit
long to intNoExplicit cast required
double to intNoDecimal part is removed
decimal to doubleMay lose precisionExplicit conversion

This table shows why C# does not allow every conversion automatically. If the target type might not represent the source value correctly, the compiler requires explicit intent.

Overflow During Conversion

Overflow happens when a value is too large or too small for the target type. For example, a long value may not fit inside an int. In such cases, conversion can produce incorrect results or throw an exception depending on the context and method used.

long big = 5000000000;
// int small = (int)big; // risky conversion

checked and unchecked Conversions

C# provides checked and unchecked contexts for controlling overflow behavior in numeric conversions and arithmetic.

checked
{
    long big = 5000000000;
    int small = (int)big;
}

In a checked context, overflow can throw an exception instead of silently producing an unexpected value. This is useful when correctness matters more than ignoring overflow.

Culture-Aware Parsing

Parsing numbers and dates can depend on culture. Some regions use a dot as the decimal separator, while others use a comma. If your application handles international input, culture-aware parsing becomes important.

using System.Globalization;

decimal amount = decimal.Parse("1234.50", CultureInfo.InvariantCulture);

Use invariant culture for machine-readable formats and explicit culture rules for user-facing regional input.

Converting User Input

Console input is read as a string. If the user enters a number, the program still receives text first. You must convert that text before using it as a numeric value.

Console.Write("Enter age: ");
string? input = Console.ReadLine();

if (int.TryParse(input, out int age))
{
    Console.WriteLine($"Age: {age}");
}
else
{
    Console.WriteLine("Please enter a valid age");
}

This pattern is safer than directly calling int.Parse() because user input can be empty, misspelled, or invalid.

Date and Time Conversion

Strings can also be converted into date and time values using DateTime.Parse() or DateTime.TryParse().

string dateText = "2026-04-22";

if (DateTime.TryParse(dateText, out DateTime date))
{
    Console.WriteLine(date.ToShortDateString());
}

Date conversion should be handled carefully because date formats can vary by region and application requirement.

Enum Conversion

C# can convert strings to enum values using Enum.Parse() or Enum.TryParse(). The safer version is TryParse().

enum Status
{
    Pending,
    Approved,
    Rejected
}

string input = "Approved";

if (Enum.TryParse(input, out Status status))
{
    Console.WriteLine(status);
}

This is useful when reading configuration values, command names, dropdown selections, or API text into strongly typed enum values.

Custom Type Conversion

Advanced C# also supports user-defined conversion operators in custom types. This allows a class or struct to define how it converts to or from another type. This feature should be used carefully because unclear implicit conversions can make code harder to understand.

Convert.ToString and Null Values

One small but useful difference is how Convert.ToString() handles null compared with calling ToString() directly. Calling ToString() on a null reference causes an error, but Convert.ToString() can safely return an empty string for null input.

object? value = null;
string text = Convert.ToString(value);

This can be useful in display logic, but you should still think carefully about whether an empty string is the right representation for missing data.

How to Choose the Right Conversion Method

  • Use implicit conversion when the compiler allows it safely.
  • Use casting when you intentionally accept possible data loss.
  • Use TryParse() when input may be invalid.
  • Use Parse() only when invalid input should be treated as an error.
  • Use Convert methods when converting between common compatible types.
  • Use is pattern matching when checking object types safely.

The safest conversion method depends on where the data comes from. Internal trusted values and external user input should not always be handled the same way.

Common Conversion Errors

  • Trying to convert invalid text to a number.
  • Losing decimal data when casting double to int.
  • Overflowing a smaller numeric type.
  • Unboxing to the wrong type.
  • Using Parse() on unpredictable user input.
  • Assuming all conversions are automatic.
What is implicit conversion in C#?

Implicit conversion is automatic conversion done by the compiler when the conversion is considered safe, such as converting an int to a long.

What is explicit conversion in C#?

Explicit conversion is manual conversion requested by the programmer using a cast, such as converting a double to an int.

Should I use Parse or TryParse?

Use TryParse() for user input or uncertain data. Use Parse() only when you are confident the input is valid or when exceptions are acceptable.

Best Practices for Type Conversion in C#

  • Prefer implicit conversion only when it is naturally safe.
  • Use explicit casting carefully when data loss is possible.
  • Use TryParse() for user input.
  • Validate external data before conversion.
  • Be careful when converting floating-point values to integers.
  • Avoid unnecessary boxing and unboxing.
  • Use clear conversion methods so intent is visible.

Type conversion in C# helps values move safely between different types. Once you understand implicit conversion, explicit casting, parsing, TryParse, boxing, and safe type checks, you can handle input and data transformations with much more confidence.