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 😅
13 Replies
the
Add
method doesn't add an array to the list
it adds an instance of Digits
to the listOoooh. Of course!
It's an object. Makes sense. Thanks!
if you want, you could override
ToString
I was thinking of that but I really just wanted to try it the hard way 😅
List can be used to add, let's say integers or strings as well. How would I create a list from tmpobj declared at top?
Its integers in mind
i'm not sure what you mean
Hm nevermind.
I guess foreach is only for lists?
foreach is for anything that implements
IEnumerable
anything that you can... enumerate
if you want to enumerate over an instance of Digits
, you'd have to have that class implement IEnumerable<int>
(presumably)Hm okay, that is a bit over my expertise right now 😝
I'm aware IEnumerable is an (interface?) but I don't know much about it.
So in my case, foreach isn't exactly ideal to write out the integer array from the class object?
it's just not even possible
unless you do
foreach (int i in tmpobj.num)
Ah... Thanks a lot!
Makes great sense. I think I was confused about list, object and datatypes!
Ero#1111
REPL Result: Success
Console Output
Compile: 664.115ms | Execution: 75.350ms | React with ❌ to remove this embed.
love ya modix
never fail to disappoint me
with the goddamn indentations
Great post!
Impressive bot btw!