0

I'm trying to compare if item is already existing in listview.
It says :

Use of unassigned local variable 'alreadyInList'

bool alreadyInList; 
foreach (var itm in lvCart.Items) 
{
     if (itm == item) 
     {
         alreadyInList = true; 
         break; 
     }

}
if(!alreadyInList)
{
      lvCart.Items.Add(new ListViewItem(new string[] { item, price, noi }));
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
bluffer
  • 31
  • 10
  • possible duplicate of [Use of unassigned local variable 'flag'](http://stackoverflow.com/questions/3384939/use-of-unassigned-local-variable-flag) – neminem Feb 18 '14 at 17:30

3 Answers3

0

You need to assign alreadyInList because it may not be assigned by the time you attempt to use it in the if statement (because your chain of code paths leave the possibility of the variable not being assigned in time):

bool alreadyInList; 

Or using linq:

bool alreadyInList = lvCart.Items.Any(itm => item == itm);

The C# compiler is usually very good at telling you what is wrong, you just need to pay attention to it.

Adam Houldsworth
  • 63,413
  • 11
  • 150
  • 187
0

Error is pretty clear.If your if statement is not executed your variable never will be assigned.Give it a default value when you defining it

bool alreadyInList = false;
Selman Genç
  • 100,147
  • 13
  • 119
  • 184
0

Others have said how you can avoid the definite assignment problem. Local variables always need to be definitely assigned before they are first read.

However, I'd suggest using LINQ to make the code simpler anyway:

bool alreadyInList = lvCart.Items.Contains(item);

(Depending on the type of Items, you may need something like lvCart.Items.Cast<SomeType>().Contains(item).)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194