C# Type Casting

Converting between different data types

🔄 What is Type Casting?

Type casting is converting a value from one data type to another in C#. It allows you to work with different types of data together, ensuring compatibility and flexibility in your programs.


// Converting between types
int myInt = 10;
double myDouble = myInt;  // Implicit casting
Console.WriteLine(myDouble); // Output: 10

double anotherDouble = 9.78;
int anotherInt = (int)anotherDouble; // Explicit casting
Console.WriteLine(anotherInt); // Output: 9
                                    

Output:

10

9

Types of Casting

⬆️

Implicit Casting

Automatic conversion (safe)

int num = 100;
double dbl = num;
⬇️

Explicit Casting

Manual conversion (may lose data)

double dbl = 9.78;
int num = (int)dbl;
🔧

Convert Methods

Using built-in conversion methods

string str = "123";
int num = Convert.ToInt32(str);
📝

Parse Methods

Converting strings to numbers

string str = "456";
int num = int.Parse(str);

🔹 Implicit Casting

Implicit casting in C# allows for automatic type conversion when there is no risk of data loss. The compiler safely converts a smaller data type to a larger, compatible type without requiring extra syntax. For example, an int can be implicitly cast to a long, float, or double. This seamless conversion is possible because the target type can accommodate the entire range of values from the source type, making operations between different numeric types more convenient and reducing the need for explicit, manual conversion in safe scenarios.

// Implicit casting (automatic)
// Order: byte -> short -> int -> long -> float -> double

int myInt = 9;
double myDouble = myInt;  // int to double

Console.WriteLine(myInt);    // Output: 9
Console.WriteLine(myDouble); // Output: 9

// More examples
byte myByte = 10;
int myInt2 = myByte;     // byte to int

float myFloat = 5.5f;
double myDouble2 = myFloat; // float to double

Console.WriteLine(myInt2);    // Output: 10
Console.WriteLine(myDouble2); // Output: 5.5

Output:

9

9

10

5.5

🔹 Explicit Casting

Explicit casting in C# is required when converting a larger type to a smaller type, which risks data loss or overflow. You must manually specify the cast using parentheses with the target type name, like (int)myDouble. This action tells the compiler you are aware of the potential consequences, such as truncation of decimal places. For instance, converting a double value of 9.78 to an int results in 9. It's a powerful but careful operation used when you need to extract a specific part of a value or interface with APIs requiring a certain type.

// Explicit casting (manual)
double myDouble = 9.78;
int myInt = (int)myDouble;  // double to int (loses decimal part)

Console.WriteLine(myDouble); // Output: 9.78
Console.WriteLine(myInt);    // Output: 9 (decimal part removed)

// More examples
long myLong = 123456789;
int myInt2 = (int)myLong;    // long to int

float myFloat = 10.99f;
int myInt3 = (int)myFloat;   // float to int

Console.WriteLine(myInt2);   // Output: 123456789
Console.WriteLine(myInt3);   // Output: 10

Output:

9.78

9

123456789

10

🔹 Using Convert Methods

The Convert class provides a robust, flexible set of methods for type conversion beyond simple casting. Methods like Convert.ToInt32(), Convert.ToDouble(), and Convert.ToString() handle conversions between base types, including strings, and offer better handling for null values compared to direct casting. They are particularly useful for converting user input, database values, or when you need conversions that involve rounding or formatting. The Convert class is a cornerstone for safe and reliable data transformation in real-world C# applications.

// Using Convert class
int myInt = 10;
double myDouble = Convert.ToDouble(myInt);
Console.WriteLine(myDouble); // Output: 10

double anotherDouble = 9.78;
int anotherInt = Convert.ToInt32(anotherDouble);
Console.WriteLine(anotherInt); // Output: 10 (rounds to nearest)

// Converting strings to numbers
string strNumber = "123";
int number = Convert.ToInt32(strNumber);
Console.WriteLine(number); // Output: 123

string strDouble = "45.67";
double doubleNum = Convert.ToDouble(strDouble);
Console.WriteLine(doubleNum); // Output: 45.67

Output:

10

10

123

45.67

🔹 Parse and TryParse Methods

The Parse and TryParse methods are essential for converting string representations to numeric types. int.Parse("100") converts a string to an integer but throws an exception if the string is invalid. The safer alternative is int.TryParse("100", out result), which returns a boolean indicating success or failure without throwing an exception, storing the result in an out parameter. TryParse is the preferred method for handling user input or external data where format errors are common, as it enables elegant error handling and validation.

// Using Parse method
string str1 = "100";
int num1 = int.Parse(str1);
Console.WriteLine(num1); // Output: 100

string str2 = "3.14";
double num2 = double.Parse(str2);
Console.WriteLine(num2); // Output: 3.14

// Using TryParse (safer - doesn't throw error)
string str3 = "200";
int num3;
bool success = int.TryParse(str3, out num3);

if (success)
{
    Console.WriteLine(num3); // Output: 200
}

// TryParse with invalid input
string invalid = "abc";
int result;
bool isValid = int.TryParse(invalid, out result);
Console.WriteLine(isValid); // Output: False

Output:

100

3.14

200

False

🔹 Converting to String

Converting any data type to a string in C# is straightforward using the ToString() method. Every object inherits this method, which returns a string representation of its value. For numeric types, dates, and booleans, it provides a standard format. This conversion is vital for displaying data to users (e.g., in console output or UI), concatenating values into messages (e.g., "Age: " + age.ToString()), and logging. For custom objects, you can override the ToString() method to provide a meaningful textual representation, enhancing debuggability and user experience.

// Converting to string
int number = 123;
string str1 = number.ToString();
Console.WriteLine(str1); // Output: 123

double price = 19.99;
string str2 = price.ToString();
Console.WriteLine(str2); // Output: 19.99

bool isActive = true;
string str3 = isActive.ToString();
Console.WriteLine(str3); // Output: True

// Combining with other strings
int age = 25;
string message = "Age: " + age.ToString();
Console.WriteLine(message); // Output: Age: 25

Output:

123

19.99

True

Age: 25

🔹 Common Casting Scenarios

Choosing the right type conversion method is key to writing robust and efficient C# code. Use implicit casting for safe, lossless promotions (int to long). Use explicit casting when you consciously accept potential data loss (double to int). Rely on the Convert class for conversions involving strings or nullable types. For parsing user input, always prefer TryParse over Parse to avoid runtime exceptions. Mastering these scenarios ensures your applications handle data correctly, maintain precision where needed, and provide clear error handling for invalid conversions, leading to more stable software.

// Scenario 1: Calculations with different types
int a = 10;
double b = 5.5;
double result = a + b; // int implicitly cast to double
Console.WriteLine(result); // Output: 15.5

// Scenario 2: Getting integer part of decimal
double price = 19.99;
int dollars = (int)price; // Explicit cast
Console.WriteLine(dollars); // Output: 19

// Scenario 3: User input (always string)
string userInput = "25";
int userAge = int.Parse(userInput);
Console.WriteLine("User is " + userAge + " years old");
// Output: User is 25 years old

Output:

15.5

19

User is 25 years old

🧠 Test Your Knowledge

Which casting happens automatically without data loss?