Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about array subscripting in C#

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.

like image 944
Michael J Avatar asked Jan 06 '11 14:01

Michael J


1 Answers

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; }
        }
    }
like image 80
Henk Holterman Avatar answered Sep 20 '22 04:09

Henk Holterman