Initialize multidimensional array

We can use the literal matrix to initialize a multidimensional array.

 
using System;

class Program
{
    static void Main(string[] args)
    {
        int[,] matrix = new int[,]
            {
              {0,1,2},
              {3,4,5},
              {6,7,8}
            };

        for (int i = 0; i < matrix.GetLength(0); i++)
        {
            for (int j = 0; j < matrix.GetLength(1); j++)
            {
                Console.Write(matrix[i, j]);
            }
            Console.WriteLine();
        }

    }
}
  

The output:


012
345
678

Jagged array can be initialized as follows:

 
using System;

class Program
{
    static void Main(string[] args)
    {
        int[][] matrix = new int[][]
            {
              new int[] {0,1,2}, 
              new int[] {3,4,5,999}, 
              new int[] {6,7,8}
            };

        for (int i = 0; i < matrix.Length; i++)
        {
            for (int j = 0; j < matrix[i].Length; j++)
            {
                Console.Write(matrix[i][j]+",");
            }
            Console.WriteLine();
        }
    }
}
  

The output:


0,1,2,
3,4,5,999,
6,7,8,
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.