views:

159

answers:

3
private bool ValidDateCheck(){

 bool _isValid = true;
 try{
  DateTime.Parse("07/&*/2009");
  DateTime d = Convert.ToDateTime("07/&*/2009");
 }
 catch{
  _isValid = false;
 }
 return _isValid;
}

How does the above code not throw an exception?

+1  A: 

The code doesn't throw an exception because exceptions are thrown at run time, and this code never runs. I know it never runs because there's no way it would compile with single quotes for the string literals. You need to use double quotes for the strings.

If the single quotes are just a typo, please edit the question and I'll take another look.

Joel Coehoorn
It's also missing semicolons. :)
Esteban Araya
sorry about that, it is in double quotes, it was a misprint on myside
TampaRich
private bool ValidDateCheck(){ bool _isValid = true; try{ DateTime.Parse("10/ DateTime d = Convert.ToDateTime("10/ } catch{ _isValid = false; } return _isValid; }
TampaRich
That is not really a useful answer, you'd better have put this into a comment...
MartinStettner
@Martin: it made more sense when I posted it. At the time there was a different code snippet with no mention of .net 1.1, and so it looked like maybe was supposed to be a trick question.
Joel Coehoorn
@Joel: Ok, excuse accepted, -1 removed :-) ...
MartinStettner
A: 

use DateTime.TryParse()

devio
His code is not throwing an exception, which is the question at hand here. TryParse will not help him.
Philip Wallace
TryParse() is not in the 1.1 framework
TampaRich
Tryparse is also not available in the 1.1 framework.
Erich
I understood the question that the code did raise an exception, and OP wants to avoid it. 1.1 comment and tag have been added after my answer.
devio
+5  A: 

This is from the .NET 1.1 documentation:

The string s is parsed using the formatting information in a DateTimeFormatInfo initialized for the current culture.

This method attempts to parse s completely and avoid throwing FormatException. It ignores unrecognized data if possible and fills in missing month, day, and year information with the current time. If s contains only a date and no time, this method assumes 12 A.M. Any leading, inner, or trailing white space character in s is ignored.

Parameter s must contain the representation of a date and time in one of the formats described in the DateTimeFormatInfo topic.

I am unable to test this as the earliest version I can build with in VS2008 is 2.0.

Philip Wallace