3️⃣ C# Variables, Data Types & Type Systems
Estimated reading: 3 minutes 256 views

C# Type Casting / C# Type Conversion – Convert Between Data Types Safely


Introduction – Why Type Conversion Matters in C#

In C#, variables must match their declared data types. However, real-world applications often involve converting data between different types β€” for example, converting a string to a number or an integer to a float. This process is called type casting or type conversion.

In this guide, you’ll learn:

  • The difference between implicit and explicit conversions
  • How to convert between types using casting and conversion methods
  • Safe casting techniques using TryParse()
  • Best practices and common pitfalls

Core Concept – What Is Type Casting?

Type casting or type conversion is the process of changing a variable from one data type to another.

Categories:

Conversion TypeDescriptionExample
Implicit CastingSafe conversion done automaticallyint to double
Explicit CastingManual conversion using cast operatordouble to int
Type ConversionUsing helper methods like Convert.ToInt32()String to integer
Safe ParsingPrevent runtime errors with TryParse()Input validation

Implicit Conversion – Done Automatically

int a = 100;
double b = a;  // Implicit conversion
Console.WriteLine(b);  // Output: 100

Safe because there’s no loss of data.


Explicit Conversion – Using Cast Operator

double x = 9.7;
int y = (int)x;  // Explicit casting
Console.WriteLine(y);  // Output: 9

Risk of data loss (decimal part truncated).


Using Convert Class

string str = "123";
int number = Convert.ToInt32(str);
Console.WriteLine(number);  // Output: 123

Throws an exception if conversion fails.


Safe Conversion with TryParse

string input = "200";
int value;

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

Use TryParse when accepting user input or working with uncertain data.


Tips, Pitfalls & Best Practices

Tip: Use TryParse() for safe user input validation.

Pitfall: Casting from a larger type to a smaller type can result in overflow or data loss.

Best Practice: Prefer Convert or TryParse over manual casting for strings and user input.


Comparison Table – Type Conversion Methods

MethodUsageSafe?Notes
Implicit Castingint β†’ doubleNo data loss
Explicit Casting(int)x RiskyMay lose data
Convert.ToX()Convert.ToInt32(string) RiskyThrows exceptions on failure
Parse()int.Parse(string) RiskyCrashes if invalid
TryParse()int.TryParse(string, out value)Safe and recommended

Code Example – Full Conversion Demo

using System;

class TypeConversionDemo
{
    static void Main()
    {
        int i = 42;
        double d = i;  // Implicit

        double x = 9.8;
        int y = (int)x;  // Explicit

        string str = "123";
        int parsed;

        if (int.TryParse(str, out parsed))
        {
            Console.WriteLine($"Safe conversion: {parsed}");
        }

        Console.WriteLine($"Implicit: {d}, Explicit: {y}");
    }
}

Output:

Safe conversion: 123  
Implicit: 42, Explicit: 9

Summary – Recap & Next Steps

C# supports multiple ways to convert between data types. Choosing the right method ensures safe and efficient execution.

Key Takeaways:

  • Use implicit casting when no data is lost
  • Use explicit casting with care
  • Prefer TryParse() for user input
  • Avoid Parse() unless data is guaranteed valid

Coming up: Explore C# Nullables to handle undefined values safely in value types.


FAQ – C# Type Casting

What is the difference between cast and Convert?
A cast changes type directly; Convert uses helper methods and handles more scenarios.

Can I convert a string to an integer?
Yes, use int.Parse(), Convert.ToInt32(), or int.TryParse() for safer conversion.

What happens if conversion fails?
Parse() and Convert throw exceptions. TryParse() safely returns false.

When should I use TryParse()?
Use it whenever converting input that might be invalid (e.g., from a user or file).

What is boxing and unboxing in C#?
Boxing converts value types to object; unboxing retrieves the value. Example: object obj = 5; int x = (int)obj;


Share Now :
Share

πŸ“¦ C# Type Casting / C# Type Conversion

Or Copy Link

CONTENTS
Scroll to Top