Fast array copy in C#

I would checkout the System.Buffer.BlockCopy if you are really concerned about speed.

http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx

Simple Example:

  int[] a = new int[] {1,2,3,4,5,6,7,8};
  int[] b = new int[a.Length];
  int size = sizeof(int);
  int length = a.Length * size;               
  System.Buffer.BlockCopy(a, 0, b, 0, length);

Great discussion on it over here: Array.Copy vs Buffer.BlockCopy


This post is old, but anyone in a similar situation as the OP should have a look at fixed size buffers in structs. They are exactly what OP was asking for: an array of primitive types with a constant size stored directly in the class.

You can create a struct to represent your collection, which will contain the fixed size buffer. The data will be stored directly within the struct, which will be stored directly within your class. You can copy through simple assignment.

They come with a few caveats:

  • They can only be used with primitive types.
  • They require the "unsafe" keyword on your struct.
  • Size must be known at compile time.

It used to be that you had to use the fixed keyword and pointers to access them, but recent changes to C# catering to performance programming have made that unnecessary. You can now work with them just like arrays.

public unsafe struct MyIntContainer
{
    private fixed int myIntegers[12];

    public int this[int index]
    {
        get => this.myIntegers[index];
        set => this.myIntegers[index] = value;
    }
}

There is no built-in bound checking, so it would be best for you to include that yourself on such a property, encapsulating any functionality which skips bound checks inside of a method. I am on mobile, or I would have worked that into my example.