Xiaosu
Xiaosu

Reputation: 615

Use of unassigned local variable when variable will always be assigned

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;
     }

  }

Upvotes: 0

Views: 3593

Answers (4)

sa_ddam213
sa_ddam213

Reputation: 43596

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;
     ...

Upvotes: 0

Ken Thai
Ken Thai

Reputation: 76

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".

Upvotes: 0

rexcfnghk
rexcfnghk

Reputation: 15452

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.

Upvotes: 1

carlosfigueira
carlosfigueira

Reputation: 87238

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.

Upvotes: 2

Related Questions