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.
Default member initializer (C++11) [edit] This is the initialization performed when an object is constructed with no initializer.
The Default value for static variables in C language is zero. The static variable memory can be used until the program completes. The default value of static values is zero.
Default values MAY be defined on struct members. Defaults appear at the end of a field definition with a C-like = {value} pattern.
You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.
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;
                        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?
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