Is there a faster way then to simply catch an exception like below?
try
{
date = new DateTime(model_.Date.Year, model_.Date.Month, (7 * multiplier) + (7 - dow) + 2);
}
catch (Exception)
{
// This is an invalid date
}
Is there a faster way then to simply catch an exception like below?
try
{
date = new DateTime(model_.Date.Year, model_.Date.Month, (7 * multiplier) + (7 - dow) + 2);
}
catch (Exception)
{
// This is an invalid date
}
As the comment pointed out by GenericTypeTea, this code will not run any faster than what you have now. However, I believe you gain in readability.
The fastest way to validate a date is an one-liner:
Using a DateTime constructor or any parse function or any exception handler will slow down the validation. TryParse is preferred only if you want to validate a string.
Look at the
DateTime.TryParse
methodHmm... think of it this way: the model_ class has a DateTime property
, so no need to validate the year & month. The only tricky part is the day of the month:
So a very quick and efficient way to validate this (which is better than throwing and catching) is to use the DateTime.DaysInMonth method:
Another benefit is that you don't need to instantiate a new DateTime just to validate this information.
P.S. Updated the code to ensure that multiplier is <= 4. That only makes sense, since any value >=5 will fail the DaysInMonth test...
One thing though: Exceptions are for exceptional cases. Bogoformatted strings are not exceptional but expected, so TryParse is more appropriate.
Using try/catch for checking validness is misuse and misconception of exceptions, especially with a catch-all catch (the latter already caused me searching for hours for why something doesn't work, and that many times).
I don't know about faster, but
Should do the same thing.
I'd be interested if anyone can tell me if this is faster (in terms of processor time) than the way described in the question.