Apologies if this issue has already come up: I have looked on the questions asked and googled but did not see any explanation.
I am starting to use C#, after nearly 30 years of C, a few months of Java and a couple of years of C++ 15 years ago ... which may explain my perplexity. In C#, if I want an array of int, I can do:
int[] a = new int[10];
At this point, I can access the elements of the array
a[0] = 1; // This is OK
I now have a class (say, SomeClass) and I want to create an array of these:
SomeClass[] o = new SomeClass[10]
I would expect (for symmetry) that I can access the elements of the array, but
a[0].someField = val; // exception, must do a[0] = new SomeClass(); first
So, the first new[]
really only allocates 10 pointers, not 10 objects, despite the syntax. I have to repeat that my knowledge of C# is not perfect (:)), so please correct me if I am wrong, but another problem with this (aside from what in my opinion is a confusion between values and references) is memory fragmentation: with C I would have allocated 10 "pointers" (malloc(10 * sizeof (void *));
, then allocated the whole area (malloc(10 * sizeof (SomeClass))
, then used offsets to initialize the array of pointers to point to the area just malloc'd, minimizing the memory fragmentation ... is there anything similar in C#?