Parse()
methodParse()
converts the string
data type to another data type. Before using Parse()
, we have to make sure the conversion will take place successfully. Otherwise, the program will crash.
To convert string
into any data type, we use the following syntax:
data_type.Parse(string);
Parse()
receives one string
parameter to be converted to the desired data type.
Parse()
returns the converted value.
Consider the following example where two strings are converted to int
and float
data types. These conversions happen successfully and the result is printed on the console:
string var_string = "4.5";Console.WriteLine(int.Parse("4") + 3);Console.WriteLine(float.Parse(var_string) + 4.4f);
Line 3: The int.Parse()
method converts the string, "4"
, into an integer value of 4
.
Line 4: The float.Parse()
method converts the variable of string, "4.5"
, into a float value of 4.5
.
Consider the following example where conversion fails:
Console.WriteLine(int.Parse("Seven") + 1);
The string "Seven"
cannot be converted into an int
value. Therefore, the method call of int.Parse()
above produces an exception of the incorrect format.
TryParse()
methodTryParse()
converts the string
data type into another data type. It returns 0
if the conversion fails. TryParse()
is a safer approach because it does not terminate the execution of the program.
Use the following syntax to convert string
into any variable.
data_type.TryParse(string, out output_variable);
The TryParse()
method receives two parameters. The first parameter is the string
to be converted. The second parameter is the variable to store the converted value. The out
keyword is used before the second parameter.
The TryParse()
method returns True
or False
value based on successful or unsuccessful conversion.
string textExample = "Seven";Console.WriteLine(textExample);int textExampleInt;int.TryParse(textExample, out textExampleInt);// "Seven" cannot be converted to int, hence textExampleInt store 0 value.Console.WriteLine(textExampleInt);string textExample2 = "5.5";Console.WriteLine(textExample2);float textExampleFloat;float.TryParse(textExample2, out textExampleFloat);// "5.5" will be converted to float value 5.5 and stored in textExampleFloatConsole.WriteLine(textExampleFloat);
int.TryParse()
method cannot convert the string "Seven"
into an integer value. Therefore, an integer value 0
will be stored in textExampleInt
.float.TryParse()
method converts the string, "5.5"
, into a float value and stores it in textExamplefloat
variable.Note: To convert any variable to a
string
, theToString()
method can be used. For example,7.ToString()
will convert7
into the string value,"7"
.
Free Resources