C# Notes: Arrays

1. Creating an array instance

    Arrays are reference types, regardless of the type of their elements. This means that an array variable refers to a contiguous block of memory holding the array elements on the heap.

    This rule applies regardless of the type of the data items in the array. Even if the array contains a value type such as int, the memory will still be allocated on the heap.

     Creating arrays follows the same pattern as creating a class instance: when you declare an array variable, you do not declare its size and no memory is allocated (other than to hold the reference on the stack). The array is given memory only when the instance is created, and this is also the point at which you specify the size of the array.

      Syntax: int[] a = new int[4];

      In other words, C# arrays are dynamically allocated !

 

2. Array syntax

      Some correct codes:

int[] a = {1, 2, 4}
int[] b = new int[3] {1, 2, 4};
int[] c = new int[3];
int[] d = new int[] {1, 3, 5, 7}

var d = { 1, 4, 5, "adsfjkdf" } // the compiler regard this as an array of strings
var e = new[] {
    new {Name = "John", Age = 17},
    new {Name = "Wenke", Age = 20},
    new {Name = "youwen", Age = 19}
} // The fields in the anonymous types must be the same for each element of the array.

     

3. Passing and returning arrays

      It is important to remember that arrays are reference types. The modifications on an array parameter are visible for every reference of the array, including the actual argument.

      For example, a bubble sort in C#

public int[] bubble(int[] list)
{
    int temp = 0;
    for (int i = list.Length; i > 0; i--)
    {
        for (int j = 0; j < i - 1; j++)
        {
            if (list[j] > list[j + 1])
            {
                temp = list[j];
                list[j] = list[j + 1];
                list[j + 1] = temp;
            }
        }
    }
    return list;
}

 

4. Copying arrays

      Arrays are reference types(In fact, each array is an instance of class System.Array), thus when you copy an array variable, you actually end up with two references to the same array instance. This is called “shallow copy”

      If you want to copy the content of an array, you must allocate another array of the same size. Then you can either copy the array element-by-element, or call System.Array.CopyTo() member method.

int[] a = {1, 2, 3, 4};
int[] b = new int[a.Length];
a.CopyTo(b);

5. Multidimensional Arrays

      In C#, there does exist the concept of multidimensional arrays.

      For example, initializing a matrix of 4 rows and 40 columns

int[,] items = new int[4, 40];

      Multidimensional arrays can consume a lot of memory. If the application uses only some of thedata in each column, allocating memory for unused elements is a waste. In this scenario, you can use a jagged array.

      Attention: jagged array and multidimensional array are different data types!

class ArrayTest
{
    static void Main()
    {
        // Declare the array of two elements:
        int[][] arr = new int[2][];

        // Initialize the elements:
        arr[0] = new int[5] { 1, 3, 5, 7, 9 };
        arr[1] = new int[4] { 2, 4, 6, 8 };

        // Display the array elements:
        for (int i = 0; i < arr.Length; i++)
        {
            System.Console.Write("Element({0}): ", i);

            for (int j = 0; j < arr[i].Length; j++)
            {
                System.Console.Write("{0}{1}", arr[i][j], j == (arr[i].Length - 1) ? "" : " ");
            }
            System.Console.WriteLine();            
        }
        // Keep the console window open in debug mode.
        System.Console.WriteLine("Press any key to exit.");
        System.Console.ReadKey();
    }
}
/* Output:
    Element(0): 1 3 5 7 9
    Element(1): 2 4 6 8
*/

C# Notes: Arrays

上一篇:C#作业总结 (5)


下一篇:12-15winform--窗体