配列 きほんのき

集合

配列

配列は、同じ型のデータをまとめて扱うための固定長の領域です。

可変長を簡単に扱えるコレクションクラスにより出番は減りましたが、重要性は変わりません。

C#(.NET)の配列はSystem.Arrayクラスを暗黙的に継承する参照型です。
            int[] array = new int[] { 100, 200, 300, 400, 500 };

            // 添え字でアクセス
            int value1 = array[3];                // 400
            
            // System.Arrayクラスのメンバを使用
            int size = array.Length;             //   5
            int value2 = (int)array.GetValue(3); // 400

初期化

配列を初期化する文法はいろいろあります。
            int[] array1 = new int[5];                     // 型と要素数を指定
            int[] array2 = new int[5] { 1, 2, 3, 4, 5 };   // 型と要素数と要素を指定
            int[] array3 = new[] { 1, 2, 3, 4, 5 };        // 型や要素数は省略(要素から推定可能)
            int[] array4 = { 1, 2, 3, 4, 5 };              // 3.0以降ではこういう書き方も出来る

多次元配列と配列の配列

            // 多次元配列 
            int[,] array5 = new int[3, 5];
            // 配列の配列
            int[][] array6 = new int[][] { new int[3], new int[5], new int[2] };
            // こういう書き方もあり
            int[][] array7 =
            {
                new int[3], 
                new int[5], 
                new int[2]
            };

引数としての配列

参照渡が必要な場合があり
        static void Main(string[] args)
        {
            int[] array8 = { 100, 200, 300, 400, 500 };
            int[] array9 = { 100, 200, 300, 400, 500 };

            TestFanc(array8);           // 100, 200, 300, 400, 500
            TestFancRef(ref array9);    // 1, 2, 3, 4, 5 
        }

        static void TestFanc(int[] array)
        {
            // array[1] = 150; など参照先の中身を変えるならOK
            // この引数のArrayはローカルなので呼び出し元に影響しない
            array = new int[] { 1, 2, 3, 4, 5 };
        }
        static void TestFancRef(ref int[] array)
        {
            array = new int[] { 1, 2, 3, 4, 5 };
        }
集合
スポンサーリンク
C#プログラミング再入門