Hi,

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

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]).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.