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 }));
}
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)
.)
See more on this question at Stackoverflow