10

I used TryParse to parse a string to number. I need a solution to initialize out variable with default value, So when TryParse fails to convert I get my default value.

Here is the code :

long.TryParse(input.Code, out long Code = 123);
//Error CS1525  Invalid expression term '=' 

I want to strictly to use C#7 out variables standard.

Mohsen Sarkar
  • 5,910
  • 7
  • 47
  • 86
  • 4
    What do you mean `initialize with default value`? The value of an out parameter is set by the method. If you want to set a value in case of error, you'll have to write the required code. This *hasn't* changed by the way. That's how out parameters always worked – Panagiotis Kanavos May 17 '17 at 10:06
  • @PanagiotisKanavos Sorry I misunderstood out parameter.. – Mohsen Sarkar May 17 '17 at 10:07
  • Let's assume that this made sense from a language standpoint for a second - _"If not why it's not standarded"_ every feature that gets added to the language has to be designed and implemented and adds complexity to the syntax - there simply isn't enough time to do everything, whilst making sure you don't break other things elsewhere. – James Thorpe May 17 '17 at 10:09

2 Answers2

12

Whilst the out parameter itself cannot take a default value, you can achieve what you want to do with a single expression in C# 7. You simply combine the out parameter with a ternary expression:

var code = long.TryParse(input.Code, out long result) ? result : 123;
David Arno
  • 42,717
  • 16
  • 86
  • 131
5

You can't do it... The .NET runtime doesn't know anything of "success" or "failure" of long.TryParse. It only knows that TryParse has a bool return value and that after TryParse finishes, the out variable will be initialized. There is no necessary correlation between true and "there is a good value in result" and false and "there is no good value in result".

To make it clear, you could have:

static bool NotTryParse(string s, out long result)
{
    return !long.TryParse(s, out result);
}

And now? When should your default value be used?

xanatos
  • 109,618
  • 12
  • 197
  • 280
  • Yeah.. seems like I misunderstood out variables! – Mohsen Sarkar May 17 '17 at 10:08
  • 3
    @MohsenSarkar nothing to feel bad about... *most* people misunderstand "out" variables and the whole by-ref thing. For context, "out" is identical to "ref", just with some compiler tweaks re "definite assignment". And 9 times out of 10: people understand what "ref" means. A point I tried to make here: http://blog.marcgravell.com/2017/04/spans-and-ref-part-1-ref.html – Marc Gravell May 17 '17 at 10:30