Why compile error “Use of unassigned local variable”?

前端 未结 10 2180
说谎
说谎 2020-11-22 03:16

My code is the following

int tmpCnt;  
if (name == \"Dude\")  
   tmpCnt++;  

Why is there an error Use of unassigned local variabl

相关标签:
10条回答
  • 2020-11-22 04:09

    Local variables are not automatically initialized. That only happens with instance-level variables.

    You need to explicitly initialize local variables if you want them to be initialized. In this case, (as the linked documentation explains) either by setting the value of 0 or using the new operator.

    The code you've shown does indeed attempt to use the value of the variable tmpCnt before it is initialized to anything, and the compiler rightly warns about it.

    0 讨论(0)
  • 2020-11-22 04:10
    IEnumerable<DateTime?> _getCurrentHolidayList; //this will not initailize
    

    Assign value(_getCurrentHolidayList) inside the loop

    foreach (HolidaySummaryList _holidayItem in _holidayDetailsList)
    {
                                if (_holidayItem.CountryId == Countryid)
                                    _getCurrentHolidayList = _holidayItem.Holiday;                                                   
    }
    

    After your are passing the local varibale to another method like below. It throw error(use of unassigned variable). eventhough nullable mentioned in time of decalration.

    var cancelRescheduleCondition = GetHolidayDays(_item.ServiceDateFrom, _getCurrentHolidayList);
    

    if you mentioned like below, It will not throw any error.

    IEnumerable<DateTime?> _getCurrentHolidayList =null;
    
    0 讨论(0)
  • 2020-11-22 04:14

    See this thread concerning uninitialized bools, but it should answer your question.

    Local variables are not initialized unless you call their constructors (new) or assign them a value.

    0 讨论(0)
  • 2020-11-22 04:17

    Default assignments apply to class members, but not to local variables. As Eric Lippert explained it in this answer, Microsoft could have initialized locals by default, but they choose not to do it because using an unassigned local is almost certainly a bug.

    0 讨论(0)
提交回复
热议问题