I have a structure declared in C#

public struct myStruct
     int x;

I created a 2D array of structures

myStruct[,] theStruct = new myStruct[3,3];

What is the C# equivalent of the following C++ code?

theStruct[0][0].x = 50;??

Please Help

Thanks in advance

7 Years
Discussion Span
Last Post by sknake

Change your access modifier on x to public.

public int x;

And then you can access individual elements like this:

theStruct[0, 0].x = 50;

Although for all I've read, people tend to frown upon mutable value types.


Incidentally, you may see something similar to your C++ code in C#, but if you ever do, it would be referring to an array of arrays. Unlike the declaration

myStruct[,] theStruct = new myStruct[3, 3];

Where you have a nice 3 x 3 box of myStruct objects, an array of arrays is not guaranteed to be square. Consider this code:

int[][] arrayOfArraysOfInts = new int[3][];

            arrayOfArraysOfInts[0] = new int[5];
            arrayOfArraysOfInts[1] = new int[3];
            arrayOfArraysOfInts[2] = new int[100];

            arrayOfArraysOfInts[0][4] = 100;
            arrayOfArraysOfInts[1][4] = 100; // throws IndexOutOfRangeException

I have an array which is 3 arrays of integers. I can access [0][4], because array [0] is itself an array with 5 elements. However, array [1] is only an array with 3 elements, so trying to access [1][4] will throw an exception.

The point is if you see [0][0] in C#, that's legal, but not the same as working with a 2D array ([0, 0]).

Edited by apegram: n/a

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.