-1
string upgradeDate = "";
TimeSpan dateDifference;

if (!sqlDR.IsDBNull(3)) upgradeDate = sqlDR.GetString(3);
dateDifference = (DateTime.Now - Convert.ToDateTime(upgradeDate)).TotalDays;

upgradeDate is coming in from the database as string. I am also getting an unassigned variable error for upgradeDate in the last line.

Julian Declercq
  • 1,536
  • 3
  • 17
  • 32
robert woods
  • 375
  • 2
  • 7
  • 20
  • 1
    Presumably this doesn't compile? `TotalDays` returns a double value, but you're trying to assign that to `dateDifference` which is defined as a TimeSpan.. – stuartd Dec 02 '16 at 18:05
  • Any idea why I am getting the unassigned variable error for upgradeDate in the last line? – robert woods Dec 02 '16 at 18:08
  • 1
    If possible I would suggest that you always save dates in a DB in a date data type and not as a string. – juharr Dec 02 '16 at 18:08
  • 1
    [Why compile error “Use of unassigned local variable”?](http://stackoverflow.com/questions/9233000/why-compile-error-use-of-unassigned-local-variable) – stuartd Dec 02 '16 at 18:09
  • @stuartd Except that `upgradeDate` is assigned. Makes me really wonder if this is the actual code that produced that compilation error. – juharr Dec 02 '16 at 18:10
  • @juharr dateDifference isn't assigned.. – stuartd Dec 02 '16 at 18:11
  • @stuartd But it's not being used, it's actually being assigned the wrong type, so I would expect this code to give a compilation error about implicitly converting a `double` to a `TimeSpan`. In fact the only way this code gives the error the OP is talking about is if you remove the `= ""` from the first line. – juharr Dec 02 '16 at 18:12
  • @juharr oh yes. I got confused by the code: yet another case of confusion caused by improper formatting of `if` clauses – stuartd Dec 02 '16 at 18:15

1 Answers1

2

You can go this way:

TimeSpan? dateDifference = null;

if (!sqlDR.IsDBNull(3)) {
   string upgradeDate = sqlDR.GetString(3);
   dateDifference = DateTime.Now - Convert.ToDateTime(upgradeDate);
}

If sqlDR.IsDBNull(3) then dateDifference will be null.

You can also start with TimeSpan dateDifference = TimeSpan.Zero; It's up to you.

But for sure you have to read this: Why compile error "Use of unassigned local variable"?, as @stuartd said.

Community
  • 1
  • 1
romanoza
  • 4,775
  • 3
  • 27
  • 44