Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference Array in C#?

Tags:

arrays

c#

I have byte array:

byte[] alldata = new byte[1024];

then I need to convert this data to UInt32:

UInt32[] block32 = new UInt32[(int)Math.Ceiling((double)alldata.Length / 4)];
Buffer.BlockCopy(alldata, 0, block32, 0, alldata.Length);

after this I need to convert block32 back to byte array.

The question is whether I can have the block32 array just be a 32-bit reference array of my byte array to avoid converting to UInt32 and back?

like image 668
Pablo Avatar asked Jan 07 '13 11:01

Pablo


People also ask

What is array reference in C?

Passing arrays to functions in C/C++ are passed by reference. Even though we do not create a reference variable, the compiler passes the pointer to the array, making the original array available for the called function's use. Thus, if the function modifies the array, it will be reflected back to the original array.

What is reference array?

Array references can be used anywhere a reference to type Object is called for, and any method of Object can be invoked on an array. Yet, in the Java virtual machine, arrays are handled with special bytecodes. As with any other object, arrays cannot be declared as local variables; only array references can.

Can we create array of reference in C?

An array of references is illegal because a reference is not an object. According to the C++ standard, an object is a region of storage, and it is not specified if a reference needs storage (Standard §11.3. 2/4). Thus, sizeof does not return the size of a reference, but the size of the referred object.

Can array be passed by reference?

The only reason for passing an array explicitly by reference is so that you can change the pointer to point to a different array. If a function only looks at the contents of an array, and does not change what is in the array, you usually indicates that by adding const to the parameter.


1 Answers

Your question isn't entirely clear - but a reference is only ever to a single object, and an array object "knows" its real type... you can't just treat a uint[] as if it were a byte[] or vice versa.

Now what you could do is hide that behind another object. You could have a single byte array which is shared between an ByteArrayView and an UInt32ArrayView where those classes each know how to address a single underlying byte array. You'd have to write those classes yourself though - I don't believe they exist anywhere in the existing framework.

You could potentially create an abstract class or interface which those disparate classes would implement, too, e.g.

class ByteArrayView : IArrayView<byte>
class UInt32ArrayView : IArrayView<uint>

(Or just implement IList<T> appropriately, of course...)

like image 111
Jon Skeet Avatar answered Sep 23 '22 01:09

Jon Skeet