前提
- Linqは使いたくないものとします。
- staticクラス内で定義しない(拡張メソッドにしない)場合は、引数のthisを取ってください。
やりたいこと
- 文字列が
null
や""
でないかでチェックするIsNullOrEmpty ()
を、配列やコレクションでも使いたい。
コード
- 素直に、配列なら
Length
で、コレクションならCount
でチェックします。
using System.Collections.Generic;
static class CollectionHelper {
/// <summary>Collection<T>がnullまたは空であれば真</summary>
public static bool IsNullOrEmpty<T> (this ICollection<T> collection) {
return (collection is null || collection.Count == 0);
}
}
-
System.Collections.Generic
を使いたくない(配列だけでいい)場合は、以下のようになります。
static class CollectionHelper {
/// <summary>T []がnullまたは空であれば真</summary>
public static bool IsNullOrEmpty<T> (this T [] array) {
return (array is null || array.Length == 0);
}
}