C#C
C#4y ago
Ice_

Arrays in constructors and lists

I have made a constructor taking an array of int (int[] numbers) in a new class, let's call the class Digits.
I have made a public property to an array of int in the class called num (with get; set;).

I then make a new object in my main class and assign some numbers, three of them:
Digits tmpobj = new(new int[] { 16,23,51 });

I then try to make a list:
List<Digits> myList = new List<Digits>();
myList.Add(tmpobj);

If I do a Console.Writeline(tmpobj.num[0]); it will return 16. If I increment it with one I get 23 etc.
I then do a foreach (var item in myList).

I've done a breakpoint after that and I see that myList in this case shows [0] .num[0] = 16, next 23 etc.
Then I've done a Console.Writeline after each item and it's just returning the int32 stuff,

I thought the "Add" method would add the full array to the list but it does not. I can see that stuff isn't right but I'm not sure how to fix this at the moment. Please help 😅
Was this page helpful?