My code is the following
int tmpCnt;
if (name == \"Dude\")
tmpCnt++;
Why is there an error Use of unassigned local variabl
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 guarantes that. If you ask how? the error message you got is the answer. Once you call their constructors, they got inialized with their default values.
int tmpCnt; // not accepted
int tmpCnt = new Int(); // defualt value applied tmpCnt = 0
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.
The following categories of variables are classified as initially unassigned:
The following categories of variables are classified as initially assigned:
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.
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 where as:
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);
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.