Complete C# Tutorial

Type Conversion in C# with Examples

What is Type Conversion?

Imagine you have a small backpack and a big suitcase. It’s easy to put things from the small backpack into the big suitcase because there’s plenty of room. But if you try to put everything from the big suitcase into the small backpack, it won’t fit unless you take some things out.

In the same way, type conversion in C# is when you change one data type into another.

Sometimes, the change happens automatically (like putting small things in the big suitcase). Other times, you need to help it happen (like carefully packing a small backpack).

Let’s explore this step by step!

 

Two Types of Type Conversion

1️⃣ Implicit Conversion (Automatic Conversion)
2️⃣ Explicit Conversion (Manual Conversion or Casting)

 

1️⃣ Implicit Conversion (Automatic)

C# automatically converts smaller data types into larger ones because there’s no risk of data loss.

 

Real-Life Example

Imagine transferring items from small backpacks to a suitcase. It fits easily, so no problem!

Code Example:
				
					using System;

class Program
{
    static void Main()
    {
        // Declare an integer variable
        int num = 100;

        // Implicit conversion: int to double
        double bigNum = num; // Automatic conversion

        // Display the result
        Console.WriteLine("Integer value: " + num);
        Console.WriteLine("Converted double value: " + bigNum);
    }
}
				
			

Output

				
					Integer value: 100
Converted double value: 100				
			

Explanation:

Implicit Conversion happens automatically because a double can hold larger values, including whole numbers, without any issues.
✅ You don’t need to do anything extra—C# does it all for you!

Common Implicit Conversions:

  1. int → long
  2. int → float
  3. int → double
  4. char → int

2️⃣ Explicit Conversion (Manual Casting)

When converting a larger type into a smaller one, C# doesn’t do it automatically. You need to force the conversion.

Real-Life Example

Imagine trying to fit all your clothes from a big suitcase into a tiny backpack. You have to be careful, or it just won’t fit!

Code Example:

				
					using System;

class Program
{
    static void Main()
    {
        // Declare a double variable with a decimal value
        double price = 9.99;

        // Manual conversion from double to int (casting)
        int roundedPrice = (int)price; // Removes the decimal part

        // Display the result
        Console.WriteLine("Original price: " + price);
        Console.WriteLine("Rounded price: " + roundedPrice);
    }
}
				
			

Output

				
					Original price: 9.99
Rounded price: 9				
			

Explanation:

Manual Casting: The (int) before the variable price tells C# to change the double value into an int. Since int can’t hold decimal numbers, it just removes the .99 part and gives you 9.

Common Explicit Conversions:

From To Method
double → int
(int) value
float → int
(int) value
long → int
(int) value

Using Convert Class for Safe Conversion

C# provides the Convert class to handle conversions safely.

Example:

				
					using System;

class Program
{
    static void Main()
    {
        // Declare a string variable with a numeric value
        string numberText = "50";

        // Convert the string to an integer using Convert.ToInt32()
        int number = Convert.ToInt32(numberText);

        // Add 10 to the converted number and display the result
        Console.WriteLine("Original number + 10 = " + (number + 10));
    }
}
				
			

Output

				
					Original number + 10 = 60				
			

Explanation:

  • Convert.ToInt32(): This method safely converts the string "50" into an integer (int).
  • After conversion, the program adds 10 to the number (50 + 10) and displays 60.

Common Conversions Using Convert Class:

Method Converts To
Convert.ToInt32(value)
int
Convert.ToDouble(value)
double
Convert.ToString(value)
string
Convert.ToBoolean(value)
bool

Using Parse() and TryParse() for Strings

If you have numbers as text, Parse() or TryParse() helps convert them.

Example with Parse() (Throws Error if Conversion Fails)

				
					using System;

class Program
{
    static void Main()
    {
        // Declare a string variable with a numeric value
        string numberText = "123";

        // Convert the string to an integer using int.Parse()
        int number = int.Parse(numberText);

        // Add 5 to the converted number and display the result
        Console.WriteLine("Converted number + 5 = " + (number + 5));
    }
}				
			

Output

				
					Converted number + 5 = 128				
			

Explanation:

  • int.Parse(): This method converts the string "123" into an integer (int).
  • After conversion, the program adds 5 to the number (123 + 5) and displays 128.

Note: If the string contains a non-numeric value (e.g., "abc"), int.Parse() will throw an exception, causing the program to crash. So be careful with its use.

Example with TryParse() (Safer Conversion)

				
					using System;

class Program
{
    static void Main()
    {
        // Declare a string variable with a numeric value
        string numberText = "123";

        // Try to convert the string to an integer using TryParse()
        bool success = int.TryParse(numberText, out int number);

        // Check if conversion was successful
        if (success)
        {
            Console.WriteLine("Converted number: " + number);
        }
        else
        {
            Console.WriteLine("Invalid number!");
        }
    }
}				
			

Output

				
					Converted number: 123				
			

Explanation:

  • int.TryParse(): This method attempts to convert a string ("123") to an integer. It returns true if successful and false if it fails.
  • If the conversion is successful, it displays the converted number.
  • If the conversion fails (e.g., the string is "abc"), it handles the failure gracefully without throwing an exception.

This approach helps avoid runtime errors when the input is not a valid number.

Conclusion

Type conversion in C# is like moving things between different-sized backpacks. Some things fit easily (automatic conversion), while others need careful packing (manual conversion).

🔹 Use implicit conversion when the backpack is big enough to fit everything.
🔹 Use explicit conversion when you need to squeeze things into a smaller backpack, but be careful not to lose anything!
🔹 Use Convert, Parse, or TryParse when you’re unsure if everything will fit—this ensures safe packing.

Keep practicing with different types of data and conversions—it’s like finding the perfect backpack for your stuff! Happy coding!

Leave a Comment

Share this Doc

Type Conversion

Or copy link