I have a 4x4 array. I want to give some nick name (variable) to a specific element, but I found no intuitive solution.
Question: How to access a specific element by single element? I intent to use an alias for each element for future readability. Let future maintainers know every element's meaning.
int[] arr = new int[ 4,4 ];
//This code won't compile
var YtoZ = "1,2";
int value = arr[ YtoZ ]; // equivalent to arr[1,2];
I checked MSDN but its example is accessed by hardcoded value.
I tried following keywords:
- "C# access Multidimensional Array index by single variable"
- "c# specify multidimensional array by variable"
Most related post is using tuple to save it: How to Save a Multidimensional Array Index?
Other results are mostly how to declare it:
- How can I declare a two dimensional string array?
- C# declaring a 2D array
- Creating an array of two-dimensional arrays in C#
My workaround might be wrapping an array with overloaded enum value, but I feel like thinking too much.
public class wrapper
{
public enum NickName
{
X2x = 0,
X2y = 10,
Z2x = 2020,
X2z = 2000,
}
// Provide [] operator access
public object this[ NickName index ]
{
get
{
int i = (int)index % 100;
int j = (int)index / 100;
return m_Matrix[ i, j ];
}
}
float[,] m_Matrix = new float[ 4, 4 ];
}