InterviewSolution
Saved Bookmarks
| 1. |
Convert a string to int in C# |
|
Answer» A string can be converted to an integer USING the int.TryParse() method. This method returns false if the string cannot be converted into an integer. A program that demonstrates the int.TryParse() method to convert a string into int in C# is given as follows: using System.IO; using System; class Demo { public static void Main() { int num1, NUM2; string str1 = "20"; string STR2 = "apple"; if (int.TryParse(str1, out num1)) Console.WriteLine("The string 1 in int form is: " + num1); else Console.WriteLine("String 1 could not be PARSED."); if (int.TryParse(str2, out num2)) Console.WriteLine("The string 2 in int form is: " + num2); else Console.WriteLine("String 2 could not be parsed."); } }The output of the above program is given as follows: The string 1 in int form is: 20 String 2 could not be parsed.In the above program, the string str1 is converted into int and stored in num1. However, the string str2 cannot be converted into int as the string is not of a valid format. |
|