C# > Core C# > Variables and Data Types > Convert Class for Type Conversion
Basic Type Conversion using Convert Class
This snippet demonstrates basic type conversion using the Convert
class in C#. It shows how to convert strings to integers, doubles to strings, and booleans to integers.
Code Snippet
This code snippet showcases the usage of the Convert
class for converting between different data types. It uses Convert.ToInt32()
to convert a string to an integer, Convert.ToString()
to convert a double to a string, and Convert.ToInt32()
to convert a boolean to an integer. It also demonstrates converting a string to a double using Convert.ToDouble()
. The converted values are then printed to the console.
using System;
public class ConvertExample
{
public static void Main(string[] args)
{
string strValue = "123";
double doubleValue = 45.67;
bool boolValue = true;
// Convert string to integer
int intValue = Convert.ToInt32(strValue);
Console.WriteLine("String to Integer: " + intValue);
// Convert double to string
string strDouble = Convert.ToString(doubleValue);
Console.WriteLine("Double to String: " + strDouble);
// Convert boolean to integer
int intBool = Convert.ToInt32(boolValue);
Console.WriteLine("Boolean to Integer: " + intBool);
//Convert string to double
double stringToDouble = Convert.ToDouble("3.14");
Console.WriteLine("String to Double: " + stringToDouble);
}
}
Concepts Behind the Snippet
The Convert
class provides a set of static methods for converting between base data types. These methods handle null values appropriately and provide error checking. The Convert
class methods are generally preferred over direct casting, especially when dealing with user input or data from external sources, as they provide more robust error handling. They internally make use of IConvertible
interface which is implemented by primitive types in C#. The Convert
class can throw FormatException
or OverflowException
if the conversion fails. For example, when the string cannot be parsed into the expected numeric type, it throws FormatException
; when the numeric value exceeds the range of the destination type it throws OverflowException
.
Real-Life Use Case
A common use case is parsing user input from a text box in a web or desktop application. For example, if you have a text box where a user enters their age, you would use the Convert.ToInt32()
method to convert the text input to an integer for processing. Another example is reading data from a CSV file where all values are initially strings and you need to convert them to appropriate data types for analysis or calculations.
Best Practices
Always handle potential exceptions, such as FormatException
and OverflowException
, when using the Convert
class. Use a try-catch
block to gracefully handle invalid input. Consider using the TryParse
methods (e.g., int.TryParse()
) for safer conversions, as they don't throw exceptions but instead return a boolean indicating success or failure. Choose the appropriate Convert
method based on the expected data type and range of values. For instance, use Convert.ToInt16
for smaller integers and Convert.ToInt64
for larger integers. Be aware of culture-specific formatting when converting strings to numbers (e.g., decimal separators). You can use CultureInfo
to handle different number formats.
Interview Tip
Be prepared to explain the difference between casting and using the Convert
class. Casting is a more direct conversion and generally faster but can lead to data loss or exceptions if the types are not compatible. The Convert
class provides more robust error handling and type safety but may have a slight performance overhead. Also, be ready to discuss exception handling and the importance of validating user input during type conversion.
When to Use Them
Use the Convert
class when you need to convert between different data types, especially when dealing with user input, external data sources, or when you require robust error handling. Use it when you are not sure that the conversion will succeed, and you want to handle possible exceptions that could be raised during casting.
Alternatives
Alternatives to the Convert
class include direct casting (e.g., (int)doubleValue
), the TryParse
methods (e.g., int.TryParse()
), and custom parsing logic. Direct casting is suitable when you are confident that the conversion will succeed and there is no risk of data loss. TryParse
methods are safer than Convert
as they don't throw exceptions, and are preferred when parsing user input. Custom parsing logic can be used for more complex conversions or when you need to handle specific formatting requirements.
Pros
Convert
class offers robust error handling, supports a wide range of data types, and provides methods for culture-sensitive conversions.
Cons
The Convert
class may have a slight performance overhead compared to direct casting, and it can throw exceptions if the conversion fails.
FAQ
-
What happens if the string I'm trying to convert to an integer is not a valid number?
If the string is not a valid number, theConvert.ToInt32()
method will throw aFormatException
. You should use atry-catch
block to handle this exception or use theint.TryParse()
method for a safer conversion. -
What's the difference between Convert.ToInt32() and int.Parse()?
Convert.ToInt32(null)
returns 0, whileint.Parse(null)
throws anArgumentNullException
. Also,Convert.ToInt32()
usesIConvertible
interface, providing more flexibility but potentially a slight performance overhead, whileint.Parse()
is more straightforward and potentially faster.int.Parse
does not handle null values gracefully. -
When should I use TryParse instead of Convert?
UseTryParse
when you are unsure if the conversion will succeed, such as when parsing user input.TryParse
doesn't throw exceptions; instead, it returns a boolean indicating success or failure, making it a safer option.