Mohsen Sarkar
Mohsen Sarkar

Reputation: 6040

How to initialize default value to C#7 out variables?

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.

Upvotes: 10

Views: 4082

Answers (2)

David Arno
David Arno

Reputation: 43264

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;

Upvotes: 12

xanatos
xanatos

Reputation: 111930

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?

Upvotes: 5

Related Questions