I just entered the following code in the 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 get the error message "Using an unassigned local variable toDate". I did not expect this, because the if statement is only entered if "toDate" gets the value from the second TryParse.
Needless to say, you can get around it by setting the "toDate" value:
DateTime fromDate, toDate = DateTime.MinValue;
or changes to && so that both TryParses are executed regardless of the first failure.
However, I wonder why the error occurs? If the fromString and toString variables were strings, an error does not occur, and the compiler does not report an error that toDate is not assigned. So I wonder why the compiler treats string
and dynamic.ToString()
differently?
source share