Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Int32.TryParse reset the out parameter when not able to convert?

Tags:

c#

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!

like image 977
Carl Bergquist Avatar asked Jul 17 '09 07:07

Carl Bergquist


People also ask

What happens when TryParse fails?

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.

What does Int32 TryParse do?

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.

What does TryParse return if successful?

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.

What method parameter type is used by TryParse method?

The type of this parameter is System.


2 Answers

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?

like image 106
Marc Gravell Avatar answered Sep 20 '22 16:09

Marc Gravell


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.

like image 26
gimel Avatar answered Sep 24 '22 16:09

gimel