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.
If you are using .NET 3 and above, you could always create an Extension method?
[Edited to rename the method name to a more appropriate one]
No. You can't get rid of the variable but you shouldn't get a compiler warning either.
Passing a variable as
out
is "using" the variable. The compiler will not issue a warning because of that.With C#7 (since August 2016) you can use the out var construct, and then just ignore the new var in subsequent code.
TryParse
is a better option. Its just a variable that is wasted. Other options include using theConvert.ToDateTime()
within a try-catch block. But again that would not be efficient because try-catch blocks are meant to be heavy. The next option is regex. This is a better solution. I guess this gives you the result instantly than compared to the others.You can very well wrap the method like Kim Gräsman said...
I'm not suggesting you actually do this, but you could use a single helper class to make this easy for all out parameters:
Then you can call:
It's horrible, uses a public mutable field, and if your application is also executing with some malicious code, it gives that code access to the last value you've parsed... but it should work :)
Nope. I'd wrap it in a method somewhere to keep the noise out of the main flow: