0

I have something like this:

myObj.FinishDateField = DateTime.Parse(someVar);

and in the run of the program someVar happens to also be empty string.

I have read posts like this one about answering similar problem: How to manage parsing an null object for DateTime to be used with ADO.NET as DBNULL

but my problem is that the myObj.FinishDateField is some in-house type of DateTime like this: Company.Framework.Data.DbTypes.DbDateTime so those casts used in answer above are still failing. How can I utilize this to be on my in-house version of DateTime?

Community
  • 1
  • 1
Bohn
  • 26,091
  • 61
  • 167
  • 254
  • have you looked at DateTime.TryParse or try doing that within an if statement and if it fails then assign a default.. there are many options you have but not seeing what you have tried besides a single line is hard to determine what's failing ..can you edit your post to show using from the example as well as show us the exact Date that you are trying to parse..? `objFinishDateField` show how this is defined as well – MethodMan Jan 19 '15 at 21:37
  • 1
    But if the `someVar` is a valid date you could assign it to FinishDateField? – Steve Jan 19 '15 at 21:37
  • If `DateTime` is a self made, then it is possible to implement `Parse(someVar)` in such a way that it accepts a `NULL`. By the way, what behavior do you want when you pass in a `NULL`? – Sjips Jan 19 '15 at 21:38
  • Why not use `DateTime?` instead homegrown things? – DrKoch Jan 19 '15 at 21:40
  • @Steve yes, that's the old code I am working on and yeah they are just assigning it... – Bohn Jan 19 '15 at 21:40
  • Then you need to replace that Parse with TryParse, check if you have a valid date and decide what to do if the date is not valid. No exception thrown in the process – Steve Jan 19 '15 at 21:41
  • @Steve Can I add an if statement before the assignment, saying if the value on the right hand side is not empty string, then do the assignment, so it will leave it alone if it is empty string. – Bohn Jan 19 '15 at 21:52
  • Yes that's the plan, but just empty is not enough. This is the reason to use TryParse, If the passed string could be converted to a valid date then accept it, otherwise .... – Steve Jan 19 '15 at 21:56

1 Answers1

1

Use DateTime.TryParse to avoid the assignment of an invalid date.

In the simplest form (without worrying for strings that don't represent dates in the current locale form)

DateTime dt;
if(DateTime.TryParse(someVar, out dt))
   myObj.FinishDateField = dt;
Steve
  • 213,761
  • 22
  • 232
  • 286