1

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:

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 ];
    }
Louis Go
  • 2,213
  • 2
  • 16
  • 29
  • If I understand correctly, you want a reference to a specific element within your array of value types? It sounds as if you may wish to use a pointer. – George Kerwood May 28 '20 at 08:32
  • @GeorgeKerwood I just want to saving my method from returning multiple indexes or tuple. So I don't have to write `array[ tuple.item1, tuple.item2 ]`. Just `array[ variable ]` – Louis Go May 28 '20 at 08:35
  • 2
    You can easily save and pass a reference to the element itself (`ref int value = ref arr[1, 2];`). Depending on what you are [actually](https://meta.stackexchange.com/q/66377/147640) doing, this may or may not mean you don't need to pass around the address. – GSerg May 28 '20 at 08:35
  • @GSerg Thanks! This should be better than my workaround. I was wondering if there is a more intuitive way to do it. – Louis Go May 28 '20 at 08:37
  • @GSerg I did not know you could inline generate references to value types like that, very helpful, thank you. – George Kerwood May 28 '20 at 08:41
  • 1
    @LouisGo, as per GSerg, see "Ref Locals" at: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/ref-returns. Every day's a learning day. – George Kerwood May 28 '20 at 08:41

0 Answers0