-2

I was reading the book Fundamentals of Computer Programming with C#

string str = Console.ReadLine();
int Value;  
bool parseSuccess = Int32.TryParse(str, out Value);
Console.WriteLine(parseSuccess ? "The square of the number is " + (Value * Value) + " . "  : "Invalid number!" );

So my question is that in the third line bool parseSuccess = Int32.TryParse(str, out Value); the Int32.TryParse() won't it return an int value? How can that be bool? And what exactly does the keyword out mean?

Stephan Bauer
  • 9,120
  • 5
  • 36
  • 58
Ilaya Raja S
  • 415
  • 5
  • 18
  • Sorry for the formatting I can't figure out how to format it like code – Ilaya Raja S May 29 '15 at 06:05
  • 1
    true if s was converted successfully; otherwise, false. https://msdn.microsoft.com/en-gb/library/f02979c7%28v=vs.110%29.aspx – fubo May 29 '15 at 06:05
  • 6
    There's an entire manual on the C# Programming Language. You should look at it before asking basic questions on the syntax of the language. See [C# Programming Guide](https://msdn.microsoft.com/en-us/library/67ef8sbd.aspx) . For detailed reference, see the [C# Reference](http://msdn.microsoft.com/en-us/library/618ayhy6.aspx). – John Saunders May 29 '15 at 06:05
  • 1
    No, it returns `boolean` value if your string was successfully parsed or not. From documentation; Return Value, Type: `System.Boolean`; **true** if s was converted successfully; otherwise, **false**. – Soner Gönül May 29 '15 at 06:07
  • 1
    Not a good advert for the book if it doesn't explain that `TryParse` tries to parse and lets you know if it could or not. `ìnt.Parse()` would return the actual value, but would fail if `str` is not a valid representation of an int. – freedomn-m May 29 '15 at 06:09
  • @John sorry I am very new to this I will and will post better questions here if I have any. – Ilaya Raja S May 29 '15 at 06:09
  • Did you try running this code? It *must* have returned an integer or the final line wouldn't have shown the answer you expected – Sayse May 29 '15 at 06:27
  • @Sayse the function's return value is a bool, not an integer. The integer is stored in the out parameter. – phoog May 29 '15 at 06:31
  • @phoog - Yes, perhaps my wording was wrong but my point stands. Simply running this code would show that it sets the value of the integer – Sayse May 29 '15 at 06:33
  • @sayse yes I did but the confusion was between parse and tryparse so now I know the difference between the two. Thanks to all of you. A new guy might think that tryparse will return int and take bool as reference. That's also possible hence I asked. But I should have gone to the documentation instead. – Ilaya Raja S May 29 '15 at 06:33
  • 1
    Just reading the book is not enough - you should always have a compiler handy, so that you can try (and observe) everything you work with. Practice is the hard part, not the theory. To learn anything useful, you have to *actually do it*. If you tried writing the code by yourself, you would see the logic behind it - and it's quite obvious, even without understanding much C# or what `TryParse` does exactly, that the return value of the method is *not* the parsed value (the very next line uses the `Value` variable, rather than `parseSuccess`). – Luaan May 29 '15 at 06:34
  • 1
    Yes, you can trivially solve most questions like this by simply searching on google for "msdn thingYouAreLookingFor" or "C# thingYouAreLookingFor" – Sayse May 29 '15 at 06:34
  • @sayse and besides by running the code I got to know it works but is it wrong to ask why it works? – Ilaya Raja S May 29 '15 at 06:36
  • 1
    @sayse yeah it seems I should Google then SE – Ilaya Raja S May 29 '15 at 06:37
  • 1
    @IlayaRajaS - No its not, providing you show research effort – Sayse May 29 '15 at 06:37
  • @luaan true , but I do have a compiler (ideone as I'm miles away from my computer) I just like to know the underlying things and i feel it helps me most – Ilaya Raja S May 29 '15 at 06:42
  • 3
    @Sayse That is of course true. Reading your comment also made me think of a similar point, which is that the name of the variable `parseSuccess` is presumably a clue from the authors of the book to indicate the meaning of the boolean returned by the function. – phoog May 29 '15 at 06:43
  • 1
    @IlayaRajaS Yes, always Google, test, debug, think, then go back to the beginning before asking. Asking should be a last resort. Sure, that requires much more time and effort, but it ultimately pays off because you *learn* a ton more. – dandan78 May 29 '15 at 06:55
  • @dandan78 yes I will. The problem is I'm not so used to the overflow site. I use the Maths site frequently there I do my question and if I can't solve I'll try to solve it in different ways and then ask without googleing it just became a practice which unfortunately carried into the overflow site – Ilaya Raja S May 29 '15 at 07:04

3 Answers3

6

Int32.TryParse returns a Boolean to indicate whether the parsing was successful or not (if the string contained non-numeric characters then the conversion would fail).

out means that the parameter is passed by reference (this means that what is passed to the TryParse function is the memory address of your variable).

Nasreddine
  • 36,610
  • 17
  • 75
  • 94
  • Just like in c++ can't we use the & operator to do that or is it really necessary to use out? Just wondering – Ilaya Raja S May 29 '15 at 06:19
  • 2
    Different language, different syntax I guess. – Nasreddine May 29 '15 at 06:22
  • 3
    @IlayaRajaS C# actually has two kinds of reference parameters. One is indicated by the `ref` keyword, the other by `out`. An out parameter is guaranteed by the compiler to be definitely assigned by the called method; a variable passed as a ref parameter is required by the compiler to be definitely assigned before calling the method. In C#, `&` operator is only allowed in unsafe code. – phoog May 29 '15 at 06:34
  • 2
    @IlayaRajaS C# is a managed-memory language, but with certain unmanaged capabilities when in an unsafe context. `out` and `ref` are just the safe versions of `&`, which C# can also use in unsafe code - the two are very different in guarantees, even though they effectively translate to almost the same machine code. Apart from that, C# tries to avoid arcane operators - anything that can have a reasonable name will have a name. Note that while C# enforces `ref` and `out` as separate things with different usage, the underlying IL *doesn't* actually enforce `out` - it's just like `ref`, sadly. – Luaan May 29 '15 at 06:47
2

As method says,TryParse, so it means if it is able to parse or not, and that's what the boolean value indicate.

True: successfully able to parse, and the the parsed value can be retrieved from out param.

False: Not able to parse the string value into int. Instead of throwing any exception, it tells you using this boolean flag, in this case you can use default value of out param (whihch is 0) or assign some other value of your choice as below:

int intValue = int.TryParse(stringValue, out intValue) ? intValue : myDefaultValue;//mydefaultValue is int containing value of your choice

int.TryParse syntatic sugar

How the int.TryParse actually works

Community
  • 1
  • 1
Rahul R.
  • 5,965
  • 3
  • 27
  • 38
  • 1
    I'm not sure what you mean by "you can use any default value," but I suspect that you are wrong. If TryParse returns false, it will set the out param to zero. That is, of course, because a method containing an out param is required to set the value before returning. In fact, there's no way it could know what value you passed in, because a method containing an out parameter is required to write to the parameter before reading from it. – phoog May 29 '15 at 06:40
2

Part of your question seems to be:

Why is TryParse defined as bool TryParse(string, out int) instead of int TryParse(string, out bool)?

The reason is that the chosen signature allows this common pattern:

int x;
if (int.TryParse(s, out x))
    Console.WriteLine(x); //or do whatever else

With the other signature, we'd need to do this:

bool success;
int x = int.TryParse(s, out success);
if (success)
    Console.WriteLine(x); // or do whatever else

The first is slightly more concise, obviously, and in my experience, at least, a large majority of TryParse calls are used directly for flow control rather than having the return value assigned to a variable.

phoog
  • 42,068
  • 6
  • 79
  • 117
  • @IlayaRajaS that's not quite right, because the various TryParse methods are defined in different types. They are therefore not overloads of each other. That is, `bool TryParse(string value, out int result)` is a static method of `System.Int32`, while `bool TryParse(string value, out bool result)` is a static method of `System.Boolean`. – phoog May 29 '15 at 07:54
  • Ok so your answer is correct without a doubt. Thanks for the clarification – Ilaya Raja S May 29 '15 at 08:13