5

Back in the old days of C, one could use array subscripting to address storage in very useful ways. For example, one could declare an array as such.

This array represents an EEPROM image with 8 bit words.

BYTE eepromImage[1024] = { ... };

And later refer to that array as if it were really multi-dimensional storage

BYTE mpuImage[2][512] = eepromImage;

I'm sure I have the syntax wrong, but I hope you get the idea.

Anyway, this projected a two dimension image of what is really single dimensional storage.

The two dimensional projection represents the EEPROM image when loaded into the memory of an MPU with 16 bit words.

In C one could reference the storage multi-dimensionaly and change values and the changed values would show up in the real (single dimension) storage almost as if by magic.

Is it possible to do this same thing using C#?

Our current solution uses multiple arrays and event handlers to keep things synchronized. This kind of works but it is additional complexity that we would like to avoid if there is a better way.

2 Answers 2

9

You could wrap the array in a class and write 1-dimensional and 2-dimensional Indexer properties.

Without validations etc it looks like this for a 10x10 array:

    class ArrayData
    {
        byte[] _data = new byte[100];

        public byte this[int x]          
        { 
            get { return _data[x]; } 
            set { _data[x] = value; }             
        }


        public byte this[int x, int y]
        {
            get { return _data[x*10+ y]; }
            set { _data[x*10 + y] = value; }
        }
    }
Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure about your math in the 2 parameter version? Shouldn't it be _data[x * y]?
No, he's assuming a 10 by 10 grid. It should be something like x*width + y
@jjnguy: No, x*10+y is correct for a 10x10 array, but I did not state so explicitly. Edited.
1

Yes, but no.

You can allocate a multidimensional array off the bat if you like. You could also create a custom class that allows you to access its underlying data in either a single-dimension or multi-dimensional way, keeping the underlying data in sync.

You cannot, however, access a single-dimensional array with a multi-dimensional index directly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.