文字列が空かどうかを調べる IsNullOrEmpty は便利です。
if (str == null || str.Length == 0) return true; ↓ return string.IsNullOrEmpty(str);
List や配列でもこれと同じような事をしたいのですが、ありませんので自作します。
自作コード
static class CollectionArrayExtension
{
public static bool IsNullOrEmpty<T>(this ICollection<T> collection)
{
return collection == null || collection.Count == 0;
}
public static bool IsNullOrEmpty<T>(this T[] array)
{
return array == null || array.Length == 0;
}
}
拡張メソッドです。
そのため、書き方は List.IsNullOrEmpty(list) ではなく、list.IsNullOrEmpty() となります。
テストコード
List<int> a = new List<int>() { 1,2,3,4,5 };
List<int> b = new List<int>();
List<int> c = null;
// for unity
Debug.Log("1: " + a.IsNullOrEmpty());
Debug.Log("2: " + b.IsNullOrEmpty());
Debug.Log("3: " + c.IsNullOrEmpty());
// for win
//Console.WriteLine("1: " + a.IsNullOrEmpty());
//Console.WriteLine("2: " + b.IsNullOrEmpty());
//Console.WriteLine("3: " + c.IsNullOrEmpty());
結果
1: False
2: True
3: True
ついでに string も拡張メソッド
string.IsNullOrEmpty(str) を str.IsNullOrEmpty() にする拡張メソッド。
static class StringExtension
{
public static bool IsNullOrEmpty(this string str)
{
return str == null || str.Count == 0;
}
}
こういうコードは、公開ライブラリに使いづらいのが難点…。




