Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack of generic list gets cleared when pushed list is cleared

I have a little problem when i want to do some operations in c#. I will give you a little example.

Stack<List<HufmannLetter>> steps = new Stack<List<HufmannLetter>>();
List<HufmannLetter> letterList = new List<HufmannLetter>();    

while(true){

    letterList.Add("asd");
    letterList.Add("sad");

    steps.Push(letterList);
    letterlist.Clear();    
}

In this code, I want to push my linkedlist to a stack than remove all the items in the list. When I clear the list, my stack's first index disappears because it passed by reference. Am i wrong? Because I dont know why it happens.

So I use pass by value method.

Stack<List<HufmannLetter>> steps = new Stack<List<HufmannLetter>>();
List<HufmannLetter> letterList = new List<HufmannLetter>();

while(true) {

    letterList.Add("asd");
    letterList.Add("sad");

    List<HufmannLetter> tempLetterList = new List<HufmannLetter>(letterList);
    steps.Push(tempLetterList);
    letterlist.Clear();    
}

Is it a good way to solve a problem? This way it is working, but readability decreases. What do you suggest me?

Thanks...

like image 607
Berkin Akaydın Avatar asked Nov 19 '16 18:11

Berkin Akaydın


2 Answers

Just create a new List<HufmannLetter> object inside the loop and add that to the stack. Reusing the same list object won't have any performance benefits.

Stack<List<HufmannLetter>> steps = new Stack<List<HufmannLetter>>();

while(true)
{
    List<HufmannLetter> letterList = new List<HufmannLetter>();

    letterList.Add("asd");
    letterList.Add("sad");

    steps.push(letterList);
}
like image 70
Botond Botos Avatar answered Nov 01 '22 16:11

Botond Botos


You can create new List<HufmannLetter>() and give in the constructor the previous list, this will create new object which will be not cleared.

while(condition)
{
    letterList.Add("asd");
    letterList.Add("sad");

    steps.push(new List<HufmannLetter>(letterList));
    letterlist.Clear();
}

EDIT

So List<T> is reference type, you are putting the letterList in the stack. In this way you are transferring the value of the reference List<T> in the stack item. So your letterList variable reference the same object as the item in your stack. When you clear the items from letterList, they are cleared in the item of the stack too.

Check what is Reference Types

like image 1
mybirthname Avatar answered Nov 01 '22 15:11

mybirthname