Conversion
Implicit Conversion
Implicit conversions are automatically performed by the compiler when necessary.
int a = 5;
double b = a; // Implicit conversion from int to double
This does not work with all types:
int a = 5;
string b = a; // This will cause a compilation error
Explicit Conversion
Explicit conversions are performed by the programmer using casting.
int a = 5;
double b = (double)a; // Explicit conversion from int to double
Conversion Methods
Parse
The Parse
method converts a string to a specific type.
int a = int.Parse("5"); // Converts "5" to 5
This method throws an exception if the string is not a valid number.
TryParse
The TryParse
method converts a string to a specific type and returns a boolean indicating success.
int a;
bool success = int.TryParse("5", out a); // Converts "5" to 5 and returns true
There's a shorter syntax for this method:
int.TryParse("5", out int a); // Converts "5" to 5 and returns true
Convert
The Convert
class contains lots of different conversion methods.
int a = Convert.ToInt32("5"); // Converts "5" to 5
This method throws an exception if the string is not a valid number.