What is Parse() and TryParse() in C# 10?
The Parse() method
Parse() 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.
Syntax
To convert string into any data type, we use the following syntax:
data_type.Parse(string);
Parameters
Parse() receives one string parameter to be converted to the desired data type.
Return value
Parse() returns the converted value.
Example 1
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);
Explanation
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.
Example 2
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.
The TryParse() method
TryParse() 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.
Syntax
Use the following syntax to convert string into any variable.
data_type.TryParse(string, out output_variable);
Parameters
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.
Return value
The TryParse() method returns True or False value based on successful or unsuccessful conversion.
Example
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);
Explanation
- Line 5: The
int.TryParse()method cannot convert the string"Seven"into an integer value. Therefore, an integer value0will be stored intextExampleInt. - Line 13: The
float.TryParse()method converts the string,"5.5", into a float value and stores it intextExamplefloatvariable.
Note: To convert any variable to a
string, theToString()method can be used. For example,7.ToString()will convert7into the string value,"7".
Free Resources