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 l
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.
TryParse
is a better option. Its just a variable that is wasted. Other options include using the Convert.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...
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 _);
Nope. I'd wrap it in a method somewhere to keep the noise out of the main flow:
bool IsValidDate(string value)
{
DateTime result;
return DateTime.TryParse(value, out result); //result is stored, but you only care about the return value of TryParse()
}
If you are using .NET 3 and above, you could always create an Extension method?
public static bool IsValidDate(this string value)
{
DateTime date = DateTime.Null;
return DateTime.TryParse(value, out date);
}
[Edited to rename the method name to a more appropriate one]
I'm not suggesting you actually do this, but you could use a single helper class to make this easy for all out parameters:
public static class OutHelper<T>
{
[ThreadStatic]
public static T Ignored;
}
Then you can call:
if (DateTime.TryParse(text, out OutHelper<DateTime>.Ignored))
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 :)