Nebelhom Nebelhom -4 years ago 156
C# Question

2D-array as a class property - how to create them the C# way?

I am trying to create a class with a property that is a two-dimensional array. The array will hold various x,y coordinates on a grid (e.g. 0,1 or 3,7) and the size of the array is dependent on a class property called size.

How would you go about creating this array in C#? I have given my solution below, but having very little C# experience and coming from a Python background with some javascript knowledge, it feels like that there is a better solution to this problem.

Could one of you C# wizards enlighten me, please?

Thanks in advance for your help.

Here is my code:

public class Obj
int Size; // Defines length of array
int[,] Pos;

// constructor
public Obj(int size)
this.Size = size;
this.Pos = new int[size, 2];

public void set_coord(int index, int x, int y)
if (index >= this.Size) {
Console.WriteLine("Catch OutOfRangeException");
this.Pos[index, 0] = x;
this.Pos[index, 1] = y;

Answer Source

A struct is the ideal approach for this. A full blown class may not be necessary, but it depends.

public struct Coordinates
    public int coordX;  
    public int coordY;  

The property then in your class could be set like this:

var Obj = new Obj();
List<Coordinates> listOfCoords = new List<Coordinates>();
var coord = new Coordinates();
coord.X = 20;
coord.Y = 15
Obj.Pos = listOfCoords

Keep in mind that Structs cannot be inherited from, or inherit, other classes or structs, as well as a few other gotchas. If you need these features, or the data in your struct is prone to modification after it is created (in other words, the data is NOT immutable), consider a small class instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download