Null out parameters in C#?

chobo2 picture chobo2 · Sep 12, 2009 · Viewed 23.6k times · Source

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.

Answer

jeubank12 picture jeubank12 · Jul 26, 2017

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 _);