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...
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);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With