I can not separate a list to others on properties

55 Views Asked by At

**When I try to separate Cards to other lists I get Stack Overflow Exception. How can I fix it? **

I don't know which way is best. Doing it at on properties or in a method.

public static List<Card>? cards
{
    get
    {
        return cards;
    }
    set
    {
        foreach (var linesorgu in value)
        {
            if (linesorgu.line == "3" || linesorgu.line.ToLower() == "done")
            {
                done.Add(linesorgu);
                cards.Remove(linesorgu);
            }
            else if (linesorgu.line == "2" || linesorgu.line.ToLower() == "inprog")
            {
                InProg.Add(linesorgu);
                cards.Remove(linesorgu);
            }
            else if (linesorgu.line == "1" || linesorgu.line.ToLower() == "todo")
            {
                todo.Add(linesorgu);
                cards.Remove(linesorgu);
            }
            else { Console.WriteLine("Line yazımında bir yanlış var"); }
              
              cards = value;

        }
    }
1

There are 1 best solutions below

2
Guru Stron On BEST ANSWER

Your need to introduce backing field. Currently in your getter and setter your are calling the card property itself which results in "infinite" recursion which ends up with SO exception. Also note that cards.Remove(linesorgu); will not actually work because at some point you will try to modify iterated collection.

private static List<Card> _cards;
public static List<Card>? cards
{
    get
    {
        return _cards;
    }
    set
    {
        var newCards = new List<Card>();
        foreach (var linesorgu in value)
        {
            if (linesorgu.line == "3" || linesorgu.line.ToLower() == "done")
            {
                done.Add(linesorgu);
            }
            else if (linesorgu.line == "2" || linesorgu.line.ToLower() == "inprog")
            {
                InProg.Add(linesorgu);
            }
            else if (linesorgu.line == "1" || linesorgu.line.ToLower() == "todo")
            {
                todo.Add(linesorgu);
            }
            else
            {
                newCards.Add(linesorgu);
                Console.WriteLine("Line yazımında bir yanlış var");
            }
        }

        _cards = newCards;
    }
}