0

The code below (that will not be production code) will not compile because of an Use of unassigned local variable 'dateTime' Looking at it I can tell that the variable would never be unassigned at return time. Returning an out parameter in an Any clause is bad form, but why can't it compile?

 private static DateTime? ConvertStringToDateByFormat(string date) {
     DateTime dateTime;

     var acceptableDateFormats = new List<String>{
        "d/MM/yyyy",
        "d/M/yyyy",
        "d/MM/yy",
        "d/M/yy",
        "d-MM-yyyy",
        "d-M-yyyy",
        "d-MM-yy",
        "d-M-yy",
        "d.MM.yyyy",
        "d.M.yyyy",
        "d.MM.yy",
        "d.M.yy",
        "d-MMM-yyyy",
        "d-MMM-yy",
        "d MMM yyyy",
        "d MMM yy"
     };

     if (acceptableDateFormats.Any(format => DateTime.TryParseExact(date, format, CultureInfo.CurrentCulture, DateTimeStyles.None, out dateTime))) {
        return dateTime;   
     }
     else {
        return null;
     }

  }
4

4 回答 4

2

Because the lambda passed to Any may not be executed - imagine that your acceptableDateFormats were an empty collection. The compiler could be smarter and see that it was defined before and it has some values, but like many other things which the compiler could do, it probably wasn't worth the effort of the developers of the compiler to implement such thing.

于 2013-01-04T00:55:36.957 回答
1

Add to @carlosfigueira's answer: Additionally, The compiler will never know at compile-time whether your date variable can be parsed successfully and store it in your dateTime variable. Thus your dateTime variable may not be initialized when the program reaches your return dateTime statement.

于 2013-01-04T00:57:30.230 回答
0

This is because the .Net compiler is checking the syntax of your code. And as you already pointed out, the dateTime object is not instantiate, which lead to an "invalid syntax".

于 2013-01-04T01:02:11.133 回答
0

You could just assign it a value since you return null if it does not parse anyway

private static DateTime? ConvertStringToDateByFormat(string date)
{
    DateTime dateTime = DateTime.MinValue;
     ...
于 2013-01-04T01:02:59.247 回答