check if string has int in csharp

In C#, you can use the int.TryParse method to check if a string can be parsed as an integer. The TryParse method takes two arguments, the string to parse and an out parameter where the result of parsing will be stored. If the parsing is successful, TryParse returns true, otherwise, it returns false.

Here's an example:

main.cs
string str = "1234";
int result;
if (int.TryParse(str, out result))
{
    // str can be parsed as an integer
}
else
{
    // str cannot be parsed as an integer
}
162 chars
11 lines

In the above code, int.TryParse is used to check if str can be parsed as an integer. If it can be parsed, the parsed value is stored in the result variable and the code inside the if block is executed. If it cannot be parsed, the code inside the else block is executed.

gistlibby LogSnag