240
Type conversion in C# refers to converting a variable from one data type to another.
It is essential when performing operations on different data types or when data needs to be formatted correctly.
This tutorial covers:
- Implicit Type Conversion (Automatic)
- Explicit Type Conversion (Casting)
- Using Convert Class for Conversion
- Parsing Methods (int.Parse(), double.Parse())
- TryParse Method (int.TryParse(), double.TryParse())
- Type Conversion Between Objects
- Best Practices for Type Conversion
1. Implicit Type Conversion (Automatic)
Implicit type conversion happens automatically when a smaller data type is converted to a larger one without data loss.
Example of Implicit Conversion
int num = 10; double result = num; // Implicitly converts int to double Console.WriteLine(result); // Output: 10.0
- Smaller to larger type (e.g., int to double) is converted automatically.
- No data loss occurs.
Common Implicit Conversions
From | To |
---|---|
byte | short, int, long, float, double, decimal |
short | int, long, float, double, decimal |
int | long, float, double, decimal |
float | double |
2. Explicit Type Conversion (Casting)
Explicit conversion (casting) is required when converting a larger data type to a smaller one.
Example of Explicit Conversion
double price = 9.99; int intPrice = (int)price; // Explicit casting Console.WriteLine(intPrice); // Output: 9 (decimal part is lost)
- Explicit casting is required using (type)variable.
- Data loss may occur (decimal part is removed).
Casting Integer to Byte
int largeValue = 300; byte smallValue = (byte)largeValue; Console.WriteLine(smallValue); // Output: 44 (Overflow occurs)
- Caution: If the number is out of range, unexpected results may occur.
3. Using Convert Class for Conversion
C# provides the Convert class for safe type conversion.
Example of Convert Methods
double number = 12.34; int convertedInt = Convert.ToInt32(number); Console.WriteLine(convertedInt); // Output: 12 (Rounded) string str = "100"; int parsedNumber = Convert.ToInt32(str); Console.WriteLine(parsedNumber); // Output: 100
Common Convert Methods
Method | Converts To |
---|---|
Convert.ToInt32(value) | Integer (int) |
Convert.ToDouble(value) | Double (double) |
Convert.ToString(value) | String (string) |
Convert.ToBoolean(value) | Boolean (true or false) |
4. Parsing Methods (Parse())
The Parse() method converts strings to numeric types.
Example: Using Parse()
string str = "50"; int number = int.Parse(str); Console.WriteLine(number); // Output: 50
- Throws an exception if conversion fails (e.g., string str = “abc”;).
Parsing a Decimal
string amount = "99.99"; double price = double.Parse(amount); Console.WriteLine(price); // Output: 99.99
Handling Exceptions in Parse()
try { string input = "abc"; int value = int.Parse(input); Console.WriteLine(value); } catch (FormatException) { Console.WriteLine("Invalid format"); }
5. Using TryParse() to Prevent Errors
TryParse() attempts conversion without throwing an exception.
Example: Using TryParse()
string input = "100"; if (int.TryParse(input, out int result)) { Console.WriteLine($"Converted value: {result}"); } else { Console.WriteLine("Conversion failed"); }
- Returns true if successful and stores the result in out variable.
- Returns false if conversion fails.
Handling Invalid Input with TryParse()
string input = "abc"; // Invalid input if (int.TryParse(input, out int value)) { Console.WriteLine($"Parsed: {value}"); } else { Console.WriteLine("Invalid input"); }
- No exceptions are thrown, making it safer than Parse().
6. Type Conversion Between Objects
Using as for Safe Casting
The as keyword attempts to convert objects safely.
object obj = "Hello"; string text = obj as string; if (text != null) { Console.WriteLine(text); }
- Returns null if conversion fails instead of throwing an exception.
Using is for Type Checking
object obj = "Hello"; if (obj is string str) { Console.WriteLine(str); // Output: Hello }
- Checks if the object is of a specific type before casting.
7. Best Practices for Type Conversion
Use TryParse() for User Input
if (int.TryParse(Console.ReadLine(), out int result)) { Console.WriteLine("Valid number entered."); } else { Console.WriteLine("Invalid input."); }
- Prevents exceptions from invalid input.
Use Convert.ToInt32() for Safe Conversion
string str = "123"; int num = Convert.ToInt32(str);
- Handles null values without exceptions.
Use Explicit Casting When Necessary
double price = 9.99; int roundedPrice = (int)price;
- Ensures proper handling of data loss.
Check for Type Before Casting
object obj = 42; if (obj is int number) { Console.WriteLine($"Number: {number}"); }
- Prevents runtime errors.
Avoid Unnecessary Conversions
int num = 10; double result = num; // Implicit conversion, no need for explicit cast
- Let the compiler handle safe conversions.
8. Common Type Conversion Mistakes
Using Parse() Without Validation
int value = int.Parse("abc"); // Throws FormatException
- Use TryParse() instead.
Ignoring Overflow Issues
byte smallValue = (byte)300; // Output: 44 (Overflow)
- Ensure values are within range.
Casting Incompatible Types
object obj = "text"; int num = (int)obj; // InvalidCastException
- Use as or is before casting.
Conclusion
- Implicit conversion is automatic for safe type changes.
- Explicit conversion (casting) is required for potential data loss.
- Convert methods provide safe conversions.
- Parse() converts strings but throws an exception on failure.
- TryParse() safely attempts conversion without exceptions.
- Use as and is for object type checking.