Created
June 11, 2016 13:43
-
-
Save lunasorcery/ba3e8237778fab998abb099ca4bf3071 to your computer and use it in GitHub Desktop.
Sane multi-dimensional arrays in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ArrayND | |
{ | |
public class Array2D<T> | |
{ | |
private int m_width; | |
private int m_height; | |
private T[] m_data; | |
public int Width { get { return m_width; } } | |
public int Height { get { return m_height; } } | |
public Array2D(int p_width, int p_height) | |
{ | |
m_width = p_width; | |
m_height = p_height; | |
m_data = new T[p_width * p_height]; | |
} | |
public T this[int x, int y] | |
{ | |
get { SanityCheck(x, y); return m_data[y * m_width + x]; } | |
set { SanityCheck(x, y); m_data[y * m_width + x] = value; } | |
} | |
private void SanityCheck(int p_x, int p_y) | |
{ | |
#if DEBUG | |
if (p_x < 0 || p_x >= m_width || | |
p_y < 0 || p_y >= m_height) | |
{ | |
throw new IndexOutOfRangeException(); | |
} | |
#endif | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace ArrayND | |
{ | |
public class Array3D<T> | |
{ | |
private int m_width; | |
private int m_height; | |
private int m_depth; | |
private T[] m_data; | |
public int Width { get { return m_width; } } | |
public int Height { get { return m_height; } } | |
public int Depth { get { return m_depth; } } | |
public Array3D(int p_width, int p_height, int p_depth) | |
{ | |
m_width = p_width; | |
m_height = p_height; | |
m_depth = p_depth; | |
m_data = new T[p_width * p_height * p_depth]; | |
} | |
public T this[int x, int y, int z] | |
{ | |
get { SanityCheck(x, y, z); return m_data[(z * m_height + y) * m_width + x]; } | |
set { SanityCheck(x, y, z); m_data[(z * m_height + y) * m_width + x] = value; } | |
} | |
private void SanityCheck(int p_x, int p_y, int p_z) | |
{ | |
if (p_x < 0 || p_x >= m_width || | |
p_y < 0 || p_y >= m_height || | |
p_z < 0 || p_z >= m_depth) | |
{ | |
throw new IndexOutOfRangeException(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment