Skip to main content
added 422 characters in body
Source Link
Jon Skeet
  • 1.5m
  • 893
  • 9.3k
  • 9.3k

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value; if (!DateTime.TryParse(startDateTextBox.Text, out value)) { startDateTextox.Text = DateTime.Today.ToShortDateString(); } 

Reasons for preferring this approach:

  • Clearer code (it says what it wants to do)
  • Better performance than catching and swallowing exceptions
  • This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value; if (!DateTime.TryParse(startDateTextBox.Text, out value)) { startDateTextox.Text = DateTime.Today.ToShortDateString(); } 

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value; if (!DateTime.TryParse(startDateTextBox.Text, out value)) { startDateTextox.Text = DateTime.Today.ToShortDateString(); } 

Reasons for preferring this approach:

  • Clearer code (it says what it wants to do)
  • Better performance than catching and swallowing exceptions
  • This doesn't catch exceptions inappropriately - e.g. OutOfMemoryException, ThreadInterruptedException. (Your current code could be fixed to avoid this by just catching the relevant exception, but using TryParse would still be better.)
Source Link
Jon Skeet
  • 1.5m
  • 893
  • 9.3k
  • 9.3k

Don't use exceptions for flow control. Use DateTime.TryParse and DateTime.TryParseExact. Personally I prefer TryParseExact with a specific format, but I guess there are times when TryParse is better. Example use based on your original code:

DateTime value; if (!DateTime.TryParse(startDateTextBox.Text, out value)) { startDateTextox.Text = DateTime.Today.ToShortDateString(); }