How to initialize default value for C # 7 variables?

I used TryParse to parse the string. I need a solution to initialize a variable with a default value. Therefore, 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 use standard C # 7 variables.

+5
source share
2 answers

As long as the out parameter cannot accept the 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 triple expression:

 var code = long.TryParse(input.Code, out long result) ? result : 123; 
+7
source

You cannot do this .... NET runtime knows nothing about the success or failure of long.TryParse . He only knows that TryParse has a return value of bool and after the TryParse completes, 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:

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

And now? When should your default be used?

+4
source

All Articles