How to Use Convert Class in C# for Data Type Conversion
The
Convert class in C# provides methods to change data from one type to another, like Convert.ToInt32() to convert strings or other types to integers. It helps safely convert values with built-in error handling for invalid conversions.Syntax
The Convert class has many static methods to convert values between types. The general syntax is:
Convert.ToType(value)- Convertsvalueto the specifiedType.- Common methods include
ToInt32,ToDouble,ToString,ToBoolean, and more.
Each method takes an input and returns the converted value or throws an exception if conversion fails.
csharp
int number = Convert.ToInt32("123"); bool flag = Convert.ToBoolean("true"); double price = Convert.ToDouble("45.67"); string text = Convert.ToString(100);
Example
This example shows how to convert different string values to numbers and booleans using the Convert class and prints the results.
csharp
using System; class Program { static void Main() { string strNumber = "42"; string strBool = "true"; string strDouble = "3.14"; int number = Convert.ToInt32(strNumber); bool flag = Convert.ToBoolean(strBool); double pi = Convert.ToDouble(strDouble); Console.WriteLine($"Integer: {number}"); Console.WriteLine($"Boolean: {flag}"); Console.WriteLine($"Double: {pi}"); } }
Output
Integer: 42
Boolean: True
Double: 3.14
Common Pitfalls
Common mistakes when using Convert include:
- Trying to convert invalid strings (like "abc") to numbers causes exceptions.
- Null values passed to
Convertmethods can throw exceptions. - Using
ConvertwhenTryParsemethods are safer for user input.
Always validate or catch exceptions when converting user input.
csharp
using System; class Program { static void Main() { string invalidNumber = "abc"; // This will throw FormatException // int num = Convert.ToInt32(invalidNumber); // Safer way using TryParse if (int.TryParse(invalidNumber, out int num)) { Console.WriteLine($"Parsed number: {num}"); } else { Console.WriteLine("Invalid number format."); } } }
Output
Invalid number format.
Quick Reference
| Method | Description | Example |
|---|---|---|
| Convert.ToInt32(value) | Converts value to int | Convert.ToInt32("123") => 123 |
| Convert.ToDouble(value) | Converts value to double | Convert.ToDouble("3.14") => 3.14 |
| Convert.ToBoolean(value) | Converts value to bool | Convert.ToBoolean("true") => true |
| Convert.ToString(value) | Converts value to string | Convert.ToString(100) => "100" |
| Convert.ToDateTime(value) | Converts value to DateTime | Convert.ToDateTime("2024-06-01") => DateTime object |
Key Takeaways
Use Convert class methods like ToInt32 and ToBoolean to change data types safely.
Convert throws exceptions on invalid input, so validate or catch errors.
For user input, prefer TryParse methods to avoid exceptions.
Convert methods are static and easy to use for common type conversions.
Always handle null or unexpected values to prevent runtime errors.