-1

I have a created a custom type in C# called InfInt. Each InfInt object has its own list of ints declared as follows:

public List<int> Numbers = new List<int>();

Then, elsewhere in the program, I have a loop where a temporary InfInt object is needed. At the end of the loop, when temporary InfInt has been filled with information, I want to add this object to a list of InfInt objects which is declared like this: var ListOfLists = new List<InfInt>();. The following code adds the temporary InfInt object to ListOfLists list of InfInt objects:

ListOfLists.Add(Temp);

Then, right when a new iteration should start, I obviously need to clear the data in the temporary InfInt object. I use the following code for this:

Temp.Numbers.Clear();

Now comes the problem. When I clear the Temp's data, it is cleared in ListOfLists too... How should I fix this?

Giorgi Aptsiauri
  • 355
  • 1
  • 2
  • 11
  • 3
    Don't call `.Clear` but create a new `Temp` object – UnholySheep Nov 06 '18 at 17:30
  • 1
    instead of clearing, why don't you make a new object? `Temp = new InfInt();` – kks21199 Nov 06 '18 at 17:30
  • OMG, it is so simple. Thank you so much! I am new, did not know that. – Giorgi Aptsiauri Nov 06 '18 at 17:31
  • 1
    Alternatively, you could create a deep copy: https://stackoverflow.com/questions/78536/deep-cloning-objects. I don't see the need in this case though. – Fang Nov 06 '18 at 17:31
  • 1
    You start by showing a `List`, but then you never refer to that again. I'm guessing that `InfInt` is a class. I'm also assuming that `Temp` is a variable that refers to an `InfInt`. When you assign a class instance something to a variable, it no longer refers to what it used to refer, instead it refers to what you just assigned. So, if you say `var temp = Get()'; MyList.Add(temp);` it adds what temp refered to to the list. If you run that again, and the `Get` function returns a different object, temp refers to that object and that object is added to the list. – Flydog57 Nov 06 '18 at 17:35

2 Answers2

2

Instead of clearing your Temp using

Temp.Numbers.Clear();

You should make a new Temp object

Temp = new InfInt();

kks21199
  • 1,116
  • 2
  • 10
  • 29
1

InfInt is a reference type which means that temporary InfInt variable is pointing to an object. When you add it to the list and then clear it, the content of this instance is cleared.

In your loop, create a new instance of InfInt instead of re-using that temporary InfInt.

Here is a MSDN document that describes the difference between Reference Type and Value Type.

xtu
  • 417
  • 3
  • 12