I read this from msdn about Int32.TryParse()
When this method returns, contains the 32-bit signed integer value equivalent to the num
The Int32.TryParse()
method returns a boolean
value as return and provides the converted value as an out parameter. So you can check for the return boolean
value for the status.
private static void TryToParse(string value)
{
int number;
bool result = Int32.TryParse(value, out number);
if (result)
{
Console.WriteLine("Converted '{0}' to {1}.", value, number);
}
else
{
if (value == null) value = "";
Console.WriteLine("Attempted conversion of '{0}' failed.", value);
}
}
The method returns a boolean indicating success or failure. Use that. The integer is a reference parameter passed into the method, and has nothing to do with the return value of the method.
Here's the prototype of Int32.TryParse()
from the documentation. It's very clear that it returns a boolean. The second parameter is an out int
which means that argument is passed by reference, so it will be mutated by the method.
public static bool TryParse(
string s,
out int result
)
So to check success or failure, do this:
int value;
if (Int32.TryParse("0", out value))
Console.WriteLine("Parsed as " + value);
else
Console.WriteLine("Could not parse");
TryParse() returns a Boolean.
Int32 testInt;
if (!Int32.TryParse("123", out testInt))
{
MessageBox.Show("Is not a Int32!");
return; // abbrechen
}
MessageBox.Show("The parst Int32-value is " + testInt);
using C# 7 now you can declare the variable within the TryParse like ...
if (Int32.TryParse(someText, out int value))
{
// Parse successful. value can be any integer
}
else
{
// Parse failed. value will be 0.
}
No, TryParse
returns true or false to indicate success. The value of the out
parameter is used for the parsed value, or 0 on failure. So:
int value;
if (Int32.TryParse(someText, out value))
{
// Parse successful. value can be any integer
}
else
{
// Parse failed. value will be 0.
}
So if you pass in "0", it will execute the first block, whereas if you pass in "bad number" it will execute the second block.