Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null out parameters in C#?

After reading on stackoverflow that in the case of checking the format of a DateTime you should use DateTime.TryParse. After trying some regex expressions they seem to get long and nasty looking to cover lots of the formatting.

But TryParse requires an "out" parameter and since I just want to do a validation format check I don't need the actual result.

So I am left with a variable that holds the "out" result and am to do nothing with it. Is there a way so I don't have to do a out parameter?

So I get rid of this warning and stop having a variable just flying around.

like image 858
chobo2 Avatar asked Sep 12 '09 06:09

chobo2


People also ask

What is an out parameter in C?

An out-parameter represents information that is passed from the function back to its caller. The function accomplishes that by storing a value into that parameter. Use call by reference or call by pointer for an out-parameter. For example, the following function has two in-parameters and two out-parameters.

Can we pass null as argument in C?

You can pass NULL as a function parameter only if the specific parameter is a pointer. The only practical way is with a pointer for a parameter. However, you can also use a void type for parameters, and then check for null, if not check and cast into ordinary or required type.

What is parameter null?

If you want a parameter that can filter by a certain value, but when you have no value in your parameter, SQL returns no results. When the parameter has no value, SQL interprets it as null in your code. Null means no value. You can fix this problem by adding a code to fix the null case.

What is a out parameter?

The out parameter in C# is used to pass arguments to methods by reference. It differs from the ref keyword in that it does not require parameter variables to be initialized before they are passed to a method. The out keyword must be explicitly declared in the method's definition​ as well as in the calling method.


1 Answers

With C#7.0 (since August 2016) you can use the out var construct, and then just ignore the new var in subsequent code.

bool success = DateTime.TryParse(value, out var result);

If you truly do not care about the value of the result, use discards:

bool success = DateTime.TryParse(value, out _);
like image 66
jeubank12 Avatar answered Oct 14 '22 01:10

jeubank12