My code is the following
int tmpCnt;
if (name == \"Dude\")
tmpCnt++;
Why is there an error Use of unassigned local variabl
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.
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;
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.
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.