Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

c#-7.0

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.

like image 983
Mohsen Sarkar Avatar asked May 17 '17 10:05

Mohsen Sarkar


People also ask

What is default initialization in C?

Default member initializer (C++11) [edit] This is the initialization performed when an object is constructed with no initializer.

What is the default value of C?

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.

Can we set default value in struct in C?

Default values MAY be defined on struct members. Defaults appear at the end of a field definition with a C-like = {value} pattern.

How can we set default value to the variable?

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.


2 Answers

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;
like image 141
David Arno Avatar answered Sep 20 '22 14:09

David Arno


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?

like image 27
xanatos Avatar answered Sep 21 '22 14:09

xanatos