どうも、ちょげ(@chogetarou)です。
空の配列を宣言する方法を紹介します。
方法

空の配列を宣言する方法は、3つあります。
[0]
1つ目は、要素数に0を指定する方法です。
具体的には、宣言時に要素数に0を指定します。
int[] array = new int[0];
使用例
using System;
public class Sample{
public static void Main(){
int[] array = new int[0];
Console.WriteLine(array.Length); //0
}
}
[] {}
2つ目は、[]{}を使う方法です。
具体的には、配列の宣言時に「new type[] {}」を代入します。
string[] array2 = new string[] { };
使用例
using System;
public class Sample{
public static void Main(){
string[] array2 = new string[] { };
Console.WriteLine(array2.Length); //0
}
}
Array.Emtpy()
3つ目は、Array.Emptyを使う方法です。
具体的には、配列の宣言時に「Array.Empty<type>()」を代入します。
int[] array3 = Array.Empty<int>();
使用例
public class Sample{
public static void Main(){
int[] array3 = Array.Empty<int>();
Console.WriteLine(array3.Length); //0
}
}
まとめ
空の配列を宣言する方法は、次の3つです。
- [0]を使う方法
- []{}を使う方法
- Array.Empty<T>()を使う方法
コメント