How do you define an array in C#?

In C#, arrays can be defined using the following method:

  1. Define an array variable using the array type and square brackets [], then create an array instance using the new keyword and specify the length of the array.
int[] numbers = new int[5]; // 定义一个包含 5 个整数的数组
string[] names = new string[3]; // 定义一个包含 3 个字符串的数组
  1. You can directly assign initial values to an array when defining it.
int[] numbers = new int[] { 1, 2, 3, 4, 5 }; // 定义一个包含初始值的整数数组
string[] names = new string[] { "John", "Jane", "Bob" }; // 定义一个包含初始值的字符串数组
  1. You can use simplified syntax to define arrays without using the ‘new’ keyword.
int[] numbers = { 1, 2, 3, 4, 5 }; // 定义一个包含初始值的整数数组
string[] names = { "John", "Jane", "Bob" }; // 定义一个包含初始值的字符串数组

Note: In C#, the index of an array starts at 0, with the first element having an index of 0, the second element having an index of 1, and so on.

bannerAds