简体   繁体   中英

C# StackOverflowException

Problem: I am trying to update a List. If a certain item's ID already exists in the List, I want to add onto that item's quantity. If not, then I want to add another item to the list.

            cart = (List<OrderItem>)Session["cart"];

            for(int counter = cart.Count-1; counter >= 0; counter--)
            {
                if (cart[counter].productId == item.productId)
                {
                    cart[counter].productQuantity += item.productQuantity;
                }
                else if (counter == 0)
                {
                    cart.Add(item);
                }
            }

cart[counter] and item represent an instance(s) of a custom object of mine. Currently when I finally find a matching ID, everything APPEARS as though it should work, but I get a StackOverflowException thrown in my custom object class.

    public int productQuantity
    {
        get
        {
            return _productQuantity;
        }
        set
        {
            productQuantity = value;
        }
    }

It gets thrown right at the open-bracket of the "set". Could somebody please tell me what the heck is wrong because I've been going at this for the past 2+ hours to no avail. Thank you in advance.

the problem is in your setter of the productQuantity

it should read:

set
    {
        _productQuantity= value;
    }

edit (naming convention):

public class Vertex3d
{
    //fields are all declared private, which is a good practice in general 
    private int _x; 

    //The properties are declared public, but could also be private, protected, or protected internal, as desired.
    public int X
    { 
        get { return _x; } 
        set { _x = value; } 
    }
}

Replace productQuantity = value; with _productQuantity = value; (you're recurring infinitely by calling the setter over and over)

Why not just use this instead? public int productQuantity { get; set; }

But the flaw was in the _

public int productQuantity {
    get {
        return _productQuantity;
    }
    set {
        _productQuantity = value;
    }
}

cart = (List<OrderItem>)Session["cart"];
int index = cart.Find(OrderItem => OrderItem.productId == item.productId);
if(index == -1) {
    cart.Add(item);
} else {
    cart[index].productQuantity += item.productQuantity;
}
public int productQuantity
{
   get
   {
      return _productQuantity;
   }
   set
   {
      _productQuantity = value; //this should be an assignment to a member variable.
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM