[c#] Why did I get the compile error "Use of unassigned local variable"?

My code is the following

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

Why is there an error "Use of unassigned local variable tmpCnt"?

I know I didn't explicitly initialize it, but due to Default Value Table a value type is initialized with 0 anyway. The reference also reminds me:

Remember that using uninitialized variables in C# is not allowed.

But why do I have to do it explicitly if it's already done by default? Wouldn't it gain performance if I wouldn't have to do it?

This question is related to c# .net

The answer is


Local variables aren't initialized. You have to manually initialize them.

Members are initialized, for example:

public class X
{
    private int _tmpCnt; // This WILL initialize to zero
    ...
}

But local variables are not:

public static void SomeMethod()
{
    int tmpCnt;  // This is not initialized and must be assigned before used.

    ...
}

So your code must be:

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

So the long and the short of it is, members are initialized, locals are not. That is why you get the compiler error.


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.


Local variables don't have a default value.

They have to be definitely assigned before you use them. It reduces the chance of using a variable you think you've given a sensible value to, when actually it's got some default value.


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.


The following categories of variables are classified as initially unassigned:

  • Instance variables of initially unassigned struct variables.
  • Output parameters, including the this variable of struct instance constructors.
  • Local variables , except those declared in a catch clause or a foreach statement.

The following categories of variables are classified as initially assigned:

  • Static variables.
  • Instance variables of class instances.
  • Instance variables of initially assigned struct variables.
  • Array elements.
  • Value parameters.
  • Reference parameters.
  • Variables declared in a catch clause or a foreach statement.

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.


A very dummy mistake, but you can get this with a class too if you didn't instantiate it.

BankAccount account;
account.addMoney(5);

The above will produce the same error whereas:

class BankAccount
{
    int balance = 0;
    public void addMoney(int amount)
    {
        balance += amount;
    }
}

Do the following to eliminate the error:

BankAccount account = new BankAccount();
account.addMoney(5);

While value types have default values and can not be null, they also need to be explicitly initialized in order to be used. You can think of these two rules as side by side rules.

Value types can not be null ? the compiler guarantees that. If you ask how, the error message you got is the answer. Once you call their constructors, they got initialized with their default values.

int tmpCnt; // Not accepted
int tmpCnt = new Int(); // Default value applied tmpCnt = 0

The default value table only applies to initializing a variable.

Per the linked page, the following two methods of initialization are equivalent...

int x = 0;
int x = new int();

In your code, you merely defined the variable, but never initialized the object.


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;