I have a problem that as i try to remove item from any list in following way i am unable to do that … why is that so the error is “use of unassigned local variable” where is it is assigned as shown below:
public void RemoveFrmList(int ProdId)
{
int _index;
foreach (Products item in BoughtItems)
{
if (item.ProductID == ProdId)
{
_index = BoughtItems.IndexOf(item);
}
}
BoughtItems.RemoveAt(_index);
}
what can be done to remove this error?
_indexis unassigned until you go in the loop. But ifBoughtItemshas noProductitems, you will have a unnassigned variable_index. Or maybe you will never get an item withitem.ProductID == ProdID.So in other words:
To fix it, you could do something like