Click here to Skip to main content
15,881,139 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code snip is something like

C#
bool success;
foreach (object item in items)
{
    if (something)
        sucess = true;
}
if (success)
    break;


It gives me error
Use of unassign local variable 'success'

I know that if I initialize it like
bool success = false;

it will work fine.

but My question is why so? if default value of bool variable is false


Thanks

:)
Posted

In c# only the member variables gets assigned with the default values, all the local vaiabiable needs to be assigned explictely.

This is basic rule that you can’t access a variable which is not assigned any value. In you case compiler is not sure that if foreach loop will run or not and same with the if condition within for loop, thats why you are getting the error.

For example

bool success;

if(something)
{
 success= false;
}

// you will get error


bool success;

If(something)
{
success=false;
}
else
{
success=true;
}

//you will not get any error, because success will get a value in any case.
 
Share this answer
 
Khaniya wrote:
sucess = true;

Bad spelling. You should have:
success = true;

Of course, the other two answers are right.
 
Share this answer
 
I don't know why C# ignores the default values for variables, but if you create it, and only some code paths assign it, you get this error. C# sucks like that.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900