if I run this C# code
int realInt = 3;
string foo = "bar";
Int32.TryParse(foo, out realInt);
Console.WriteLine(realInt);
Console.Read();
I get 0. And I would like to know why! Cause I cannot find any reason why it would. This forces me to make temp variables for every parsing. So please! Great coders of the universe, enlighten me!
TryParse method converts a string value to a corresponding 32-bit signed integer value data type. It returns a Boolean value True , if conversion successful and False , if conversion failed. In case of failed conversion, it doesn't throw any exception and 0 is assigned to the out variable.
TryParse(String, Int32) Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. But what happens if the passed string itself is a string representation of '0'. So the TryParse will return zero.
The type of this parameter is System.
It is "out", not "ref". Inside the method it has to assign it (without reading it first) to satisfy the meaning of "out".
Actually, "out" is a language concern (not a framework one) - so a managed C++ implementation could probably ignore this... but it is more consistent to follow it.
In reality; if the method returns false you simply shouldn't look at the value; treat it as garbage until it is next assigned. It is stated to return 0, but that is rarely useful.
Also - if it didn't do this (i.e. if it preserved the value); what would this print:
int i;
int.TryParse("gibber", out i);
Console.WriteLine(i);
That is perfectly valid C#... so what does it print?
The Int32.TryParse Method (String, Int32) doc says:
Converts the string representation of a number to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
result
Type: System.Int32
When this method returns, contains the 32-bit signed integer value equivalent to the number contained in s, if the conversion succeeded, or zero if the conversion failed. The conversion fails if the s parameter is null reference (Nothing in Visual Basic), is not of the correct format, or represents a number less than MinValue or greater than MaxValue. This parameter is passed uninitialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With