言語
日本語
English

Caution

お使いのブラウザはJavaScriptが無効になっております。
当サイトでは検索などの処理にJavaScriptを使用しています。
より快適にご利用頂くため、JavaScriptを有効にしたうえで当サイトを閲覧することをお勧めいたします。

C#辞典

  1. トップページ
  2. C#辞典
  3. string.IsNullOrEmpty() / string.IsNullOrWhiteSpace()

string.IsNullOrEmpty() / string.IsNullOrWhiteSpace()

対応: IsNullOrEmpty() C# 2.0(2005)
IsNullOrWhiteSpace() C# 4.0(2010)

文字列が null または空文字列かを判定する『string.IsNullOrEmpty()』、空白のみの文字列も検出する『string.IsNullOrWhiteSpace()』、そして null の代替値を返す『??』演算子です。

構文

// 文字列が null または "" の場合に true を返します。
string.IsNullOrEmpty(string? value)

// 文字列が null、""、またはスペース・タブなど空白のみの場合に true を返します。
string.IsNullOrWhiteSpace(string? value)

// 左辺が null の場合に右辺の値を返します(null 合体演算子)。
左辺 ?? 右辺

// 左辺が null の場合に右辺を代入します(null 合体代入演算子)。
変数 ??= 値

メソッド一覧

メンバー概要
string.IsNullOrEmpty(string? value)value が null または長さ 0 の文字列の場合に true を返します。
string.IsNullOrWhiteSpace(string? value)value が null、空文字列、または空白文字(スペース・タブ・改行)のみの場合に true を返します。
??(null 合体演算子)左辺が null でなければ左辺を、null であれば右辺を返します。
??=(null 合体代入演算子)変数が null の場合にのみ右辺を代入します。

サンプルコード

Program.cs
using System;

// IsNullOrEmpty() の使い方です。
string? name1 = null;
string? name2 = "";
string? name3 = "孫悟空";

Console.WriteLine(string.IsNullOrEmpty(name1)); // True
Console.WriteLine(string.IsNullOrEmpty(name2)); // True
Console.WriteLine(string.IsNullOrEmpty(name3)); // False

// IsNullOrWhiteSpace() はスペースのみの文字列も検出します。
string? input = "   "; // スペースのみです。
Console.WriteLine(string.IsNullOrEmpty(input));      // False(IsNullOrEmpty では検出できません)
Console.WriteLine(string.IsNullOrWhiteSpace(input)); // True

// ?? 演算子で null の場合のデフォルト値を指定します。
string? username = null;
string displayName = username ?? "ゲスト";
Console.WriteLine(displayName); // ゲスト

string? theme = "ベジータ";
string selected = theme ?? "デフォルト";
Console.WriteLine(selected); // ベジータ(null でないのでそのまま使われます)

// ??= 演算子の例です。
string? cache = null;
cache ??= "初期値";
Console.WriteLine(cache); // 初期値
dotnet script string_isnullorempty.csx
True
True
False
False
True
ゲスト
ベジータ
初期値

概要

フォーム入力の検証では、ユーザーがスペースだけを入力するケースも考慮が必要です。そのような場合は『IsNullOrEmpty()』よりも『IsNullOrWhiteSpace()』を優先して使うことを推奨します。

『??』演算子は null チェックの if 文をシンプルに書けるため、デフォルト値の設定によく使われます。null 許容型(string?)の詳細は C# の null 安全設計の仕様を参照してください。

型変換のユーティリティは『Convert.ToString() / Convert.ToInt32()』を参照してください。

記事の間違いや著作権の侵害等ございましたらお手数ですがまでご連絡頂ければ幸いです。