How to define an array using variables?

In VS, you can define an array using variables using the following methods:

  1. Declare an array variable using the symbol ([ ]) and then reference the array using the variable name.
int[] numbers; // 声明一个整数数组变量
string[] names; // 声明一个字符串数组变量
  1. When initializing an array, you can use variables to specify the length of the array.
int size = 5;
int[] numbers = new int[size]; // 使用变量 size 定义一个具有指定长度的整数数组

string[] names = new string[10]; // 可以直接使用变量来指定数组长度
  1. You can use variables to initialize the elements of an array.
int[] numbers = new int[] { 1, 2, 3, 4, 5 }; // 直接指定元素来初始化整数数组

int[] numbers = new int[size] { 1, 2, 3, 4, 5 }; // 使用变量 size 定义一个具有指定长度和元素的整数数组

string[] names = new string[] { "John", "Mary", "Tom" }; // 直接指定元素来初始化字符串数组

string[] names = new string[size] { "John", "Mary", "Tom" }; // 使用变量 size 定义一个具有指定长度和元素的字符串数组
  1. You can use looping structure and variables to iterate through the elements in an array.
int[] numbers = new int[] { 1, 2, 3, 4, 5 };

for (int i = 0; i < numbers.Length; i++)
{
    Console.WriteLine(numbers[i]);
}

The above are some common methods of defining arrays using variables in Visual Studio. You can choose the method that suits your specific needs for defining and using arrays.

广告
Closing in 10 seconds
bannerAds