Use of unassigned local variable that is assigned

后端 未结 3 1975
囚心锁ツ
囚心锁ツ 2021-01-23 12:39

The below code runs a \'for\' loop to create months 1 through 12 then names each month Jan through Dec according to their number. That pieces compiles fine. At the bottom wher

3条回答
  •  感情败类
    2021-01-23 13:14

    You know that month can only take the values 1 to 12 inclusive but the compiler is not that smart. If say month is 0 then the variable monthName is never assigned a value and that is what the compiler is complaining about. To fix it simply initialize the variable when you declare it:

    string monthName = null;
    

    Also, there is something fishy about your code because monthName is used outside the loop where it is declared but I assume that this is a typo because the code as it stands now will not give you the error you are asking about.

提交回复
热议问题