LoginSignup
1
0

More than 1 year has passed since last update.

配列やリストでもIsNullOrEmpty ()を使いたい (C#)

Last updated at Posted at 2019-06-09

前提

  • Linqは使いたくないものとします。
  • staticクラス内で定義しない(拡張メソッドにしない)場合は、引数のthisを取ってください。

やりたいこと

  • 文字列がnull""でないかでチェックするIsNullOrEmpty ()を、配列やコレクションでも使いたい。

コード

  • 素直に、配列ならLengthで、コレクションならCountでチェックします。
using System.Collections.Generic;

static class CollectionHelper {
    /// <summary>Collection&lt;T&gt;がnullまたは空であれば真</summary>
    public static bool IsNullOrEmpty<T> (this ICollection<T> collection) {
        return (collection == null || collection.Count == 0);
    }
}
  • System.Collections.Genericを使いたくない(配列だけでいい)場合は、以下のようになります。
static class CollectionHelper {
    /// <summary>T []がnullまたは空であれば真</summary>
    public static bool IsNullOrEmpty<T> (this T [] array) {
        return (array == null || array.Length == 0);
    }
}
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0