❔ Fix sized array/list
I'm quite new to C#, evidently, and I'm trying to initialise a list (or an array) in a class that shall be defined when an instance of this class is made. Something like:
this code is ofcourse wrong, but I believe it should kinda explain what im trying to do.
20 Replies
so
when you do:
when the code is compiled, that initialization is actually put into the constructor ... so that's basically the same as:
performing this transformation on your code, you essentially have this:
so the first problem here is that you're initializing the thing twice
it's redundant ... only the second one will be kept, and the first is a waste of time
second, the syntax itself is wrong in the second case
well the first problem is actually that access modifiers shouldnt be pascalcase^^
you can do
new int[] { num1, num2 }
lol yeah I just silently fixed that
I haven't used C# version higher than 7, so not sure what syntaxes they've added...for the other points i fully agree what you are saying ;)
but I think the most concise way to initialize that would be
_cords = new [] { num1, num2 };
unless there's something newer
should work in newer versions
i thought in your example there would still be an int in there but after rereading you already omited it... then ignore what i wrote
okay okay
thank you goodpeople ✌️
the explicit way is
new int[2] { num1, num2 }
but the above syntax omits the type and size because they can be inferred
also, if these are coordinates, then maybe you should add a second o to the name of your field 😛whoops
do you want an inline buffer or a heap allocated one?
because you can technically do any
i just want to use the least amount of memory that i can
even just
= { num1, num2 }
worksWindows10CE#8553
REPL Result: Success
Result: int[]
Compile: 411.493ms | Execution: 66.299ms | React with ❌ to remove this embed.
the least possible would be fixed-size arrays, but you need unsafe code for those
there's the unsafe keyword for types and the fixed keyword for arrays
uh?
no you don't
if you want to use little memory here, that's easy
Windows10CE#8553
REPL Result: Success
Compile: 527.634ms | Execution: 42.235ms | React with ❌ to remove this embed.
yeah this too, but this one's not an array
not that it matters though
okay thats what im gonna implement
if you had 10 items, a tuple would be less viable
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.