I've just typed in the following code to a VS2015 .Net v4.5.2 console application:
dynamic fromString = "blah", toString = "blah2";
DateTime fromDate, toDate;
if (DateTime.TryParse(fromString.ToString(), out fromDate) && DateTime.TryParse(toString.ToString(), out toDate)) {
Console.WriteLine(fromDate);
Console.WriteLine(toDate);
}
Somewhat unexpectedly I'm getting the error "Use of unassigned local variable toDate". I didn't expected it because the if statement is only entered if 'toDate' is assigned a value from the second TryParse.
Needless to say, it can be worked around by assigning 'toDate' a value:
DateTime fromDate, toDate = DateTime.MinValue;
or changing the && to & so that both TryParses are executed regardless of the first failing.
However, I wonder why the error occurs? If the variables fromString and toString were strings, the error does not occur and the compiler does not give the error that toDate is unassigned. Therefore I wonder why the compiler treats string
and dynamic.ToString()
differently?