Paramclasses Academy - Blog

Tutorials Details

←
Post 6 of 30
→

What is Type Casting in C#: Implicit and Explicit Conversion ?

What is Type Casting in C#: Implicit and Explicit Conversion ?

October 24, 2026

Introduction

In C# programming, variables have specific data types such as int, double, float, decimal, char, and string. Sometimes, you need to convert a value from one data type to another. This process is known as type conversion.

For example, you may need to convert an integer into a decimal value, convert a decimal value into an integer, or convert text entered by a user into a numeric value for calculations.

C# supports different ways to convert data types, including implicit conversion, explicit casting, conversion methods, and parsing.

Consider this example:

int number = 10;
double result = number;

Console.WriteLine(result);

Output:

10

Here, an int value is converted into a double value automatically. This is an example of implicit conversion.

In this tutorial, you will learn how type casting works in C#, the difference between implicit and explicit conversion, how to use Convert methods and parsing methods, and how to handle conversion errors safely.

1. What Is Type Casting in C#?

Type casting is the process of converting a value from one data type to another.

For example:

int number = 100;

double result = number;

Console.WriteLine(result);

Output:

100

The integer value 100 is converted into a double.

In everyday C# programming, the terms type casting and type conversion are often used interchangeably. More precisely, casting usually refers to a conversion written using cast syntax, while type conversion is the broader process that also includes parsing and conversion methods.

Type conversion is useful when:

  • Performing calculations with different numeric types.

  • Processing user input.

  • Converting values received from files or APIs.

  • Working with database values.

  • Passing values to methods that expect specific data types.

2. Types of Type Conversion in C#

The most common conversion approaches in C# are:

Conversion Type Description Example
Implicit conversion The compiler performs an allowed conversion automatically int to double
Explicit conversion You specify the conversion using a cast double to int
Conversion methods Use methods from the Convert class Convert.ToInt32()
Parsing Convert text into a typed value int.Parse()
Safe parsing Attempt conversion without throwing an exception for invalid input int.TryParse()

Each approach serves a different purpose. Choosing the correct one helps prevent unexpected results and runtime errors.

3. Implicit Type Conversion in C#

Implicit conversion occurs automatically when C# supports a conversion between the source and destination types without requiring an explicit cast.

It is commonly used when converting a numeric type into another numeric type that can represent the source value across the source type's full range and precision requirements.

Example 1: Converting int to double

int number = 25;
double result = number;

Console.WriteLine(result);

Output:

25

The compiler automatically converts the integer to a double.

Example 2: Converting int to long

int number = 5000;
long result = number;

Console.WriteLine(result);

Output:

5000

A long can represent every value of the int type, so this conversion is implicit.

Example 3: Converting float to double

float number = 12.5f;
double result = number;

Console.WriteLine(result);

Output:

12.5

The double type has greater precision and range than float, so conversion from float to double is implicit.

Common Implicit Numeric Conversions

Source Type Destination Type Conversion
sbyte short Implicit
byte int Implicit
short int Implicit
int long Implicit
int float Implicit
int double Implicit
long double Implicit
float double Implicit

Important: An implicit conversion does not guarantee that every numeric value will be represented exactly. For example, converting a sufficiently large integer to float may lose precision even though the conversion is allowed.

Advantages of Implicit Conversion

  • It requires less code.

  • It is convenient when the conversion is supported automatically.

  • It avoids writing unnecessary cast expressions.

  • It makes many numeric operations easier to express.

4. Explicit Type Conversion in C#

Explicit conversion is required when the compiler cannot automatically perform a conversion because information might be lost or the conversion may not be valid for every possible source value.

You perform explicit conversion using a cast operator.

Syntax:

destinationType variable = (destinationType)sourceValue;

Example 1: Converting double to int

double number = 25.75;

int result = (int)number;

Console.WriteLine(result);

Output:

25

The fractional part is discarded. Casting a floating-point value to an integer does not round it to the nearest whole number; it truncates the fractional part toward zero.

Example 2: Converting float to int

float number = 18.9f;

int result = (int)number;

Console.WriteLine(result);

Output:

18

Example 3: Converting long to int

long number = 100000;
int result = (int)number;

Console.WriteLine(result);

Output:

100000

This value fits within the range of int, so the result is as expected.

However, not every long value fits within the int range. An explicit cast from long to int can produce an unexpected result if the source value is outside that range.

long number = 3000000000L;

int result = (int)number;

Console.WriteLine(result);

In the default unchecked context, the result is not 3000000000 because int cannot represent that value. The result reflects the low-order bits of the source value.

When narrowing numeric values, validate the range before conversion or use a checked conversion where appropriate.

Example 4: Checked Conversion

long number = 3000000000L;

try
{
    int result = checked((int)number);
    Console.WriteLine(result);
}
catch (OverflowException)
{
    Console.WriteLine("The value is outside the range of int.");
}

Output:

The value is outside the range of int.

The checked expression detects the overflow and throws an OverflowException rather than allowing the out-of-range integral conversion to proceed silently.

Advantages of Explicit Conversion

  • It makes potentially lossy conversions visible.

  • It gives you control over the destination type.

  • It is useful when narrowing numeric values.

  • It helps communicate the programmer's intention.

5. Difference Between Implicit and Explicit Conversion

Understanding the difference between implicit and explicit conversion is important for writing reliable C# programs.

Feature Implicit Conversion Explicit Conversion
Syntax No cast required Cast required in common narrowing conversions
Performed by Compiler Programmer specifies the cast
Typical example int to double double to int
Data loss May still lose precision in some numeric conversions May discard information or overflow
Ease of use Simpler Requires more care
Range checking Depends on the conversion A cast does not automatically guarantee safe range handling

Combined Example

int a = 50;
double b = a;

double x = 75.95;
int y = (int)x;

Console.WriteLine(b);
Console.WriteLine(y);

Output:

50
75

The first conversion is implicit, while the second is explicit.

6. Type Conversion Using the Convert Class

C# provides the System.Convert class, which includes methods for converting values between supported types.

Common methods include:

Method Purpose
Convert.ToInt32() Converts a supported value to int
Convert.ToInt64() Converts a supported value to long
Convert.ToDouble() Converts a supported value to double
Convert.ToDecimal() Converts a supported value to decimal
Convert.ToString() Converts a value to its string representation
Convert.ToBoolean() Converts a supported value to bool

Example 1: Using Convert.ToInt32()

double number = 45.8;

int result = Convert.ToInt32(number);

Console.WriteLine(result);

Output:

46

Unlike an explicit cast from double to int, Convert.ToInt32() rounds a floating-point value to the nearest integer. At an exact midpoint, it uses rounding to the nearest even integer.

Example 2: Converting a Number to double

int number = 100;

double result = Convert.ToDouble(number);

Console.WriteLine(result);

Output:

100

Example 3: Converting a Value to string

int age = 25;

string text = Convert.ToString(age);

Console.WriteLine(text);

Output:

25

The output looks the same as the original number, but text is a string rather than an integer.

Example 4: Converting a String to an Integer

string text = "123";

int number = Convert.ToInt32(text);

Console.WriteLine(number);

Output:

123

If the string is not a valid integer representation, the conversion may throw a FormatException. For user input, int.TryParse() is often a better choice.

7. Parsing in C#

Parsing converts a string representation into a typed value.

For example, a console application receives user input as text. If the application needs to perform arithmetic, it may need to parse that text into an integer or another numeric type.

Using int.Parse()

string text = "250";

int number = int.Parse(text);

Console.WriteLine(number + 50);

Output:

300

Using double.Parse()

string text = "25.5";

double number = double.Parse(text);

Console.WriteLine(number + 10);

Output:

35.5

Parsing behavior for numeric text can depend on the current culture, including decimal separators. For applications that process data from files or APIs, consider specifying an appropriate culture explicitly.

What Happens When Parsing Fails?

string text = "Hello";

// int number = int.Parse(text);

The string "Hello" is not a valid integer representation, so int.Parse() throws a FormatException.

For user-provided input, use TryParse() when invalid input is an expected possibility.

8. Using TryParse() for Safe Conversion

The TryParse() methods attempt to convert text into a specific data type without throwing an exception when the text is invalid.

They return true if the conversion succeeds and false if it fails. The parsed value is provided through an out parameter.

Example: Using int.TryParse()

string text = "123";

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

Output:

Converted value: 123

Example: Invalid Input

string text = "Hello";

if (int.TryParse(text, out int number))
{
    Console.WriteLine(number);
}
else
{
    Console.WriteLine("Please enter a valid integer.");
}

Output:

Please enter a valid integer.

Example: Reading User Input

Console.Write("Enter your age: ");

string? input = Console.ReadLine();

if (int.TryParse(input, out int age) && age >= 0)
{
    Console.WriteLine("Your age is " + age);
}
else
{
    Console.WriteLine("Please enter a valid non-negative age.");
}

This example validates both the conversion and the allowed range.

Best practice: Prefer TryParse() when you expect that input may be invalid, such as text entered by a user.

9. Converting Between char and Numeric Types

In C#, a char represents a UTF-16 code unit. It can be converted to an integer to obtain its numeric code-unit value.

Example: Converting char to int

char letter = 'A';

int code = letter;

Console.WriteLine(code);

Output:

65

The numeric value 65 is the UTF-16 code-unit value for the character A.

Example: Converting an Integer to char

int code = 66;

char letter = (char)code;

Console.WriteLine(letter);

Output:

B

The integer 66 corresponds to B in the basic Latin character range.

A char is not the same as a complete Unicode character in every case because some Unicode characters require a surrogate pair.

10. Converting Between string and Numeric Types

Converting between strings and numeric types is common when handling user input, configuration values, file data, and API responses.

String to Integer

string text = "500";

int number = int.Parse(text);

Console.WriteLine(number + 100);

Output:

600

Integer to String

int number = 500;

string text = number.ToString();

Console.WriteLine(text);

Output:

500

String to Decimal

string priceText = "199.99";

decimal price = decimal.Parse(
    priceText,
    System.Globalization.CultureInfo.InvariantCulture);

Console.WriteLine(price);

Output:

199.99

Here, InvariantCulture is used so the example consistently interprets the period as the decimal separator.

Decimal to String

decimal price = 199.99m;

string text = price.ToString(
    System.Globalization.CultureInfo.InvariantCulture);

Console.WriteLine(text);

Output:

199.99

When displaying currency to users, prefer culture-aware formatting appropriate to the user's locale.

11. Type Conversion with Different Numeric Types

C# supports multiple numeric types, each with different ranges and precision.

Data Type General Purpose
byte Small non-negative integer values
short Small signed integer values
int General-purpose integer values
long Larger integer values
float Single-precision floating-point values
double Double-precision floating-point values
decimal High-precision base-10 arithmetic, often used for financial values

Example: Integer to Decimal

int number = 100;

decimal result = number;

Console.WriteLine(result);

Output:

100

Example: Decimal to Integer

decimal price = 99.99m;

int result = (int)price;

Console.WriteLine(result);

Output:

99

The explicit cast truncates the fractional part.

Example: Double to Decimal

double value = 123.45;

decimal result = (decimal)value;

Console.WriteLine(result);

Output:

123.45

Although this example produces the expected display, floating-point values may already contain a small representation error. Converting a double to decimal does not recover information that was lost earlier, and some values are outside the range of decimal.

For financial calculations, using decimal from the beginning is often preferable.

12. Boxing and Unboxing in C#

Boxing and unboxing are conversions involving value types and the object type.

What Is Boxing?

Boxing converts a value type to object or to an implemented interface type. The value is stored in a boxed object.

int number = 100;

object boxed = number;

Console.WriteLine(boxed);

Output:

100

What Is Unboxing?

Unboxing extracts a value type from a boxed object. The target value type must match the boxed value type.

object boxed = 100;

int number = (int)boxed;

Console.WriteLine(number);

Output:

100

Incorrect Unboxing

object boxed = 100;

// long number = (long)boxed;

This throws an InvalidCastException at runtime because the boxed value is an int, not a long.

If a numeric conversion is required, first unbox to the actual stored type and then convert it.

object boxed = 100;

int original = (int)boxed;
long converted = original;

Console.WriteLine(converted);

Output:

100

Boxing and unboxing are important concepts when working with older APIs and non-generic collections. Generic collections such as List can help avoid unnecessary boxing in common scenarios.

13. Common Errors in Type Conversion

Error 1: Invalid Format

string text = "ABC";

// int number = int.Parse(text);

Problem: The text is not a valid integer representation, so parsing throws a FormatException.

Solution: Use int.TryParse() when invalid input is possible.

Error 2: Overflow

long number = 3000000000L;

// int result = checked((int)number);

Problem: The value is outside the range of int.

Solution: Validate the range or choose a destination type that can represent the value.

Error 3: Unexpected Truncation

double number = 9.99;

int result = (int)number;

Console.WriteLine(result);

Output:

9

Problem: An explicit floating-point-to-integer cast truncates the fractional part.

Solution: Use an appropriate rounding method if rounding is the intended behavior.

double number = 9.99;

int result = (int)Math.Round(number);

Console.WriteLine(result);

Output:

10

Error 4: Culture-Dependent Parsing

A numeric string such as "12,50" may be interpreted differently under different cultures.

Solution: Specify the intended culture when processing machine-readable values or external data.

Error 5: Invalid Unboxing

Attempting to unbox an object to a type different from the actual boxed value causes an InvalidCastException.

Solution: Unbox to the actual type first, then perform any required conversion.

14. Practical Example: Convert User Input into Numbers

The following program asks the user for two numbers, validates the input, and calculates their sum.

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter the first number: ");
        string? firstInput = Console.ReadLine();

        Console.Write("Enter the second number: ");
        string? secondInput = Console.ReadLine();

        if (double.TryParse(firstInput, out double firstNumber) &&
            double.TryParse(secondInput, out double secondNumber))
        {
            double sum = firstNumber + secondNumber;

            Console.WriteLine("Sum: " + sum);
        }
        else
        {
            Console.WriteLine("Please enter valid numbers.");
        }
    }
}

Sample Input:

Enter the first number: 10.5
Enter the second number: 20.5

Output:

Sum: 31

This example demonstrates how type conversion makes it possible to transform user-entered text into numeric values for calculations.

The example uses the current culture for parsing. If the application expects a specific decimal format regardless of the user's system settings, use an explicit culture and appropriate number styles.

15. Best Practices for Type Casting in C#

Follow these recommendations when converting values in C#:

  1. Prefer implicit conversion when it is supported and appropriate.

  2. Use explicit casts carefully, especially when converting to a narrower numeric type.

  3. Use TryParse() to validate potentially invalid text input.

  4. Use Parse() when the input is expected to be valid and failure should be reported.

  5. Understand the difference between truncation and rounding.

  6. Use checked when detecting integral overflow is important.

  7. Choose suitable numeric types based on range and precision requirements.

  8. Use decimal for many financial calculations rather than relying on binary floating-point arithmetic.

  9. Specify culture when parsing or formatting external data with a defined numeric format.

  10. Understand boxing and unboxing when converting between value types and object.

16. Practice Exercise

Create a C# program that accepts a product price and quantity from the user.

Requirements

  • Ask the user to enter a product price.

  • Convert the price into a decimal.

  • Ask the user to enter the quantity.

  • Convert the quantity into an integer.

  • Validate both inputs using TryParse().

  • Calculate the total price.

  • Display the result with two decimal places.

Sample Solution

using System;
using System.Globalization;

class Program
{
    static void Main()
    {
        Console.Write("Enter product price: ");
        string? priceInput = Console.ReadLine();

        Console.Write("Enter quantity: ");
        string? quantityInput = Console.ReadLine();

        bool validPrice = decimal.TryParse(
            priceInput,
            NumberStyles.Number,
            CultureInfo.InvariantCulture,
            out decimal price);

        bool validQuantity = int.TryParse(
            quantityInput,
            out int quantity);

        if (validPrice && validQuantity && price >= 0 && quantity >= 0)
        {
            decimal total = price * quantity;

            Console.WriteLine(
                "Total Price: " +
                total.ToString("F2", CultureInfo.InvariantCulture));
        }
        else
        {
            Console.WriteLine("Please enter valid non-negative values.");
        }
    }
}

Sample Input:

Enter product price: 99.99
Enter quantity: 3

Output:

Total Price: 299.97

This exercise combines string parsing, numeric conversion, input validation, and decimal arithmetic.

17. Frequently Asked Questions (FAQs)

1. What is type casting in C#?

Type casting is the process of converting a value from one data type to another. It is often used when a variable needs to be represented in a different type.

2. What is the difference between implicit and explicit conversion?

Implicit conversion is performed automatically when C# supports the conversion. Explicit conversion requires a cast or another conversion mechanism when the conversion cannot be performed implicitly.

3. What is the difference between casting and parsing?

Casting converts a value between compatible types. Parsing converts a textual representation, such as "123", into a typed value such as an integer.

4. What is the difference between int.Parse() and int.TryParse()?

int.Parse() returns the converted integer or throws an exception if conversion fails. int.TryParse() returns a Boolean indicating success or failure and provides the result through an out parameter.

5. What is the difference between (int)value and Convert.ToInt32(value)?

When converting a floating-point value, (int)value truncates the fractional part, while Convert.ToInt32(value) rounds to the nearest integer, using midpoint-to-even rounding.

6. Can a string be converted directly into an integer using a cast?

No. A string containing numeric text generally needs to be parsed or converted using an appropriate method, such as int.Parse(), int.TryParse(), or Convert.ToInt32().

7. What is overflow in C#?

Overflow occurs when a numeric result or conversion exceeds the range supported by its destination type. Depending on the operation and context, it may throw an exception or produce a different result.

8. What are boxing and unboxing?

Boxing converts a value type into object or a compatible interface representation. Unboxing extracts a value type from a boxed object and requires the correct underlying type.

9. Why should decimal be used for financial calculations?

decimal represents many base-10 fractional values more naturally than binary floating-point types, making it useful for many monetary calculations. Application-specific rounding rules are still important.

10. Which conversion method is best for user input?

TryParse() is generally a good choice because invalid input can be handled without relying on exceptions for ordinary validation failures.

18. Quiz: Test Your Knowledge

Question 1: Which conversion is normally implicit in C#?

A. double to int
B. int to double
C. string to int using a cast
D. object to an unrelated type

Question 2: What is the output of this code?

double number = 15.9;
int result = (int)number;

Console.WriteLine(result);

A. 15.9
B. 16
C. 15
D. Compilation error

Question 3: Which method is best suited to converting potentially invalid user-entered integer text?

A. int.TryParse()
B. int.ToString()
C. typeof(int)
D. Math.Round()

Question 4: What happens when int.Parse("Hello") is executed?

A. It returns 0
B. It returns null
C. It throws a FormatException
D. It returns Hello

Question 5: What is the result of Convert.ToInt32(8.5)?

A. 8
B. 9
C. 8.5
D. Compilation error

Question 6: What is boxing in C#?

A. Converting a string to an integer
B. Converting an integer to a string
C. Converting a value type to object or a compatible interface representation
D. Rounding a decimal value

Quiz Answers

  1. B — int to double

  2. C — 15

  3. A — int.TryParse()

  4. C — It throws a FormatException

  5. B — 8.5 rounds to 9 using midpoint-to-even rounding

  6. C — Converting a value type to object or a compatible interface representation

Conclusion

Type casting and type conversion are essential parts of C# programming. They allow developers to work with different data types, process user input, perform calculations, and exchange data between application components.

The most important concepts to remember are:

  • Implicit conversion: The compiler automatically performs an allowed conversion.

  • Explicit conversion: You specify a cast when required, taking care with potential data loss.

  • Convert methods: Provide a convenient way to convert supported values.

  • Parsing: Converts text into a typed value.

  • TryParse: Attempts conversion safely when invalid input is possible.

  • Boxing and unboxing: Convert between value types and object representations.

Practice these techniques with small programs to understand how different conversions behave.

←
Post 6 of 30
→