どうも、ちょげ(@chogetarou)です。
配列を空に初期化する方法を紹介します。
方法

配列を空に初期化する方法は、3つあります。
new Type[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
}
}
new Type[] {}
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<Type>()
3つ目は、Array.Empty<T>()を使う方法です。
具体的には、配列の宣言時に「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>()を使う方法
コメント