Difference Between C# Multidimensional Arrays and Jagged Arrays, i.e., the Difference Between [,] and [][]

2019年12月9日 86点热度 0人点赞 1条评论
内容目录

Declaration of Multidimensional Arrays

When declaring, the length of the array must be specified, in the format of type [length, length, length, ... ]

int [,] test1 = new int [3,3];

Alternatively, you can assign values during declaration, allowing the system to infer the length

int [,] test1 = {
            {1,2,3},
            {1,2,3},
            {1,2,3},
        };

Declaration of Jagged Arrays

When declaring, at least the length of the first dimension must be specified, in the format of type [ ] [ ] [ ] ...

int [][] test1 = new int[5][]; 
int [][] test1 = new int[][];    //Note: This declaration method is incorrect

Or assign values during declaration, allowing the system to infer the lengths

        int [][] test1 = {
            new int[] {1,2,3,4},
            new int[] {1,2,3},
            new int[] {1,2}
        };

  Similarities and Differences Between Multidimensional Arrays and Jagged Arrays

Both require specifying the lengths upon declaration; multidimensional arrays require specifying the length of each dimension, while jagged arrays only require the length of the first dimension to be specified.

A multidimensional array is declared with symbols like this [ , , , , ], where commas are inside the square brackets [ ], separating the lengths of each dimension. In contrast, a jagged array has each dimension independently within [ ].

When specifying the length of the array, it can only be done on the right side of the equals sign; int [,] test1 = new int [3,3] is correct;int [6,4] test1 = new int [6,4] is incorrect;

The following code illustrates this point

Inconsistent lengths in Multidimensional Arrays will cause errors

int [,] test1 = {
            {1,2,3,4},
            {1,2,3},
            {1,2}
        };         // This is incorrect; the lengths must be consistent

int [,] test1 = new int [4,5] {
            {1,2,3,4,5},
            {1,2,3},
            {1,2,3}
        };        // This is also incorrect; the lengths must be consistent and every position must be assigned a value

            This is a difference between C# and C language, as C allows incomplete assignments, where unassigned positions default to 0.

The following method is correct

int [,] test1 = {
            {1,2,3},
            {1,2,3},
            {1,2,3}
        };

  Initializing Jagged Arrays

The method of declaring a jagged array has already been mentioned above

  int [][] test1 = {
            new int[] {1,2,3,4},     //new int[4] {1,2,3,4}
            new int[] {1,2,3},      //new int[3] {1,2,3}
            new int[] {1,2}
        };

  

  Note that there is new int[], which is a characteristic of jagged arrays. Jagged arrays are arrays made up of arrays, and jagged arrays require creating instances for each of the internal arrays.

  That is, each dimension of a jagged array is an instance, and each instance is an array.

 

The Length of Arrays is Fixed

Both multidimensional and jagged arrays have a fixed length that cannot be changed arbitrarily.

 

Getting the Length of an Array

Use the object.Length to get the length of the array. Note that the length of a multidimensional array is the product of each dimension, which is the total number of elements.

 

        int [,] test1 = {
            {1,2,3},
            {1,2,3},
            {1,2,3}
        };
        Console.WriteLine(test1.Length);
 Output is   9

 

The length of a jagged array, on the other hand, is the “number of internal arrays” it contains, for example

 

       int [][] test1 = {
            new int[] {1,2,3},
            new int[] {1,2,3},
            new int[] {1,2,3},
        };
        Console.WriteLine(test1.Length);   
Output is 3

 

Methods

Methods for both multidimensional and jagged arrays are indistinguishable, as they both have methods like Sort() and Clear(), which will not be elaborated here. For advanced usage of arrays, please refer to

https://www.jb51.net/Special/265.htm

 

The following are properties of the System.Array class

Since there are many methods provided by the system, please refer to them if interested

https://docs.microsoft.com/zh-cn/dotnet/api/system.array?view=netframework-4.7.2


Using Arrays to Initialize Types

In C#, there are lambda, anonymous classes, etc. After C# 5.0/6.0, there are very convenient ways to declare classes, declare type types, and assign values. Below is a test example.

Example 1

Initializing collections, generic collections, etc. using arrays

Declare a List generic collection

using System.Collections.Generic;        //Header import
</span><span style="color: #008000;">//</span><span style="color: #008000;">Code in main</span>
    <span style="color: #0000ff;">static</span> <span style="color: #0000ff;">void</span> Main(<span style="color: #0000ff;">string</span><span style="color: #000000;">[] args)
    {
        List</span>&lt;<span style="color: #0000ff;">string</span>&gt; list = <span style="color: #0000ff;">new</span> List&lt;<span style="color: #0000ff;">string</span>&gt;<span style="color: #000000;">();

        Console.ReadKey();
    }
</span></pre>

Then, add an item to the collection list using the Add() method

        static void Main(string[] args)
        {
            List<string> list = new List<string>();
            //Adding
            list.Add("a");
            list.Add("b");
            list.Add("c");
            list.Add("d");
            list.Add("e");
            list.Add("f");
            list.Add("g");
            Console.ReadKey();
        }

Use “arrays” to add new items

List<string> list = new List<string>(){"a","b","c","d","e","f"}; 

List<string> list = new List<string>{"a","b","c","d","e","f"};

//Both methods above are acceptable. Pay attention to whether there are () at the end

Example 2

The above example initializes the collection directly using an array in the declaration, but it does not handle the "cool operations" very well.

Try Staggered Arrays

1. Write a class in the namespace where the program class is located

    public class Test
    {
        public int x;
        public int y;
        public void What()
        {
            Console.WriteLine(x + y);
        }
    }

2. In the Main method

       static void Main(string[] args)
        {
            List<Test> list = new List<Test>()
            {
                new Test{x=1,y=6},
                new Test{x=8,y=6},
                new Test{x=4,y=8},
                new Test{x=5,y=7},
                new Test{x=3,y=3},
                new Test{x=6,y=6},
                new Test{x=9,y=666},
                new Test{x=7,y=6},
            };
            Console.ReadKey();
        }

The complete code is as follows

    public class Test
    {
        public int x;
        public int y;
        public void What()
        {
            Console.WriteLine(x + y);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            List<Test> list = new List<Test>()
            {
                new Test{x=1,y=6},
                new Test{x=8,y=6},
                new Test{x=4,y=8},
                new Test{x=5,y=7},
                new Test{x=3,y=3},
                new Test{x=6,y=6},
                new Test{x=9,y=666},
                new Test{x=7,y=6},
            };
            Console.ReadKey();
        }
    }

 

Since classes are reference types, their memory is a reference address, unlike types like int, char, etc. Therefore, when using arrays, collections, etc., for classes (reference types), you can understand it as a "staggered array".

 

痴者工良

高级程序员劝退师

文章评论