2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

配列やリストでも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 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);
    }
}
2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?