Reputation: 478
Helloo, everyone. I have a problem with If statement. Where I'm wrong?
int cnt = 0;
int wayListNums;
foreach (TableRow tr in allVisibleRows)
{
SPListItem itemAdd = wayList.Items.Add();
if (cnt == 0)
{
wayListNums = itemAdd.ID;
}
itemAdd["wayNum"] = "WayBill № " + " " + wayListNums;
...................
This is following error :
Error 1 Use of unassigned local variable 'wayListNums' ....
Upvotes: 2
Views: 344
Reputation: 3877
The problem here is that wayListNums has no default value when it's declared. Later you are setting it's value only in if block, so if that if is not executed, the variable remains unassigned, like the error tells you.
So you have 2 options:
int wayListNums = 0;
//code
if (cnt == 0)
{
wayListNums = itemAdd.ID;
}
else
{
wayListNums = somethingElse;
}
Upvotes: 2
Reputation: 3215
In C# and other similar languages the compiler expects the value of every variable to be initialized before it can be used. In your case the compiler is not sure if the value initilized within if-block
will always be initialized and since you are using it outside the scope of this if-block
the compiler simply gives you an error that value is not initialized. Simply setting
int wayListNums = 0;
will resolved the issue.
Upvotes: 0
Reputation: 29006
The compiler not sure about the values in the collection allVisibleRows
sometimes it may be null or empty, (the variable get value only when the collection is non-empty as well as if (cnt == 0)
evaluates to true.) In such situations the value of wayListNums
is unknown. this is the reason for the warning. to overcome this issue, Initialize the variable before use:
int wayListNums=0;// or some other value
So that the default value will be used if other conditions failed.
Upvotes: 0
Reputation: 1972
You have to assigned default value to local variable..as error suggest it is unassigned..
here int wayListNums = 0;// because of int default value 0
Upvotes: 0