LA.NET [EN]

May 24

Arrays in .NET– part VII

Posted in .NET Basics C#      Comments Off on Arrays in .NET– part VII

To wrap up this series on .NET arrays, I’ll show you how to create a fixed size buffer (aka internal arrays). A fixed size buffer is useful technique for improving the performance of your app when you need to interop with unmanaged code. To understand the gains from this approach, we’ll start with a simple example:

public struct Wrapper {
    public Int32[] Ints = new Int32[10];
}

As you probably know, struct is a value type and that means that it will be allocated in the stack (this is an implementation detail which is important when you’re after performance improvements). Now, what you probably forget is that the Int32 array won’t be stored directly in the stack. Since arrays are reference types, the array field defined in the struct will only hold a reference to the array. The array object will always be stored in the heap memory.

In these cases, sometimes it might be useful to be able to put the entire array in the stack.  We’ve already seen an option for doing this in the previous post. Fixed size buffers allow us to do that too. Here’s some code that shows how to change the previous code so that the array is completely embedded in the struct:

public unsafe struct Wrapper {
    //array embedded inline
    public fixed Int32 Ints[10];
}

The first thing to notice is that we can only embed an array in an unsafe struct (which, when you think about it, makes sense). If you want, you can apply the unsafe keyword to field (instead of applying it to the struct). Notice also that the array can only be a single dimension zero-based array of one of the basic type (ex.: Int32, Single, etc). Going through all the items of the array can be done in several ways. You can use a pointer or you can simply use the array-like syntax:

unsafe static void UnsafeAccess(){
    Wrapper aux;//creates new embedded array
    for (var i = 0; i < 10; i++) {
        aux.Ints[i] = i;
    }
    for (var i = 0; i < 10; i++) {
        Console.WriteLine(aux.Ints[i] );
    }
}

As you can see, instantiating a Wrapper will automatically instantiate an array of integers in the stack. As you’re probably expecting by now, you can only instantiate Wrapper from an unsafe context. And that’s it for now. There’s still more to say about .NET basics. Stay tuned for more.