文字列の「空」判定の重要性
アプリケーション、特にユーザー入力や外部APIからのデータを受け取る際、string(文字列)変数が意図しない値(nullや空文字列)になっているケースは頻繁に発生します。
nullの変数に対して.Lengthや.Split()などのメソッドを呼び出そうとすると、プログラムはNullReferenceExceptionという重大なエラーで停止してしまいます。
これを防ぐには、処理の実行前に文字列が「有効なデータを持っているか」を安全にチェックする必要があります。C#のstringクラスは、この判定を効率的に行うための2つの静的メソッドを提供しています。
string.IsNullOrEmpty(string str)
string.IsNullOrEmpty()は、指定された文字列が以下のいずれかである場合にtrueを返す、最も基本的なチェックメソッドです。
null: 変数がどのオブジェクトも参照していない状態。- 空文字列(
""):string.Emptyとも呼ばれ、文字数が0の文字列。
IsNullOrEmpty のコード例
ユーザーがIDを何も入力しなかった(空文字列)か、またはデータが初期化されていない(null)場合に、処理をスキップする例です。
using System;
public class IsNullOrEmptyExample
{
public static void Main()
{
string inputA = null;
string inputB = ""; // string.Empty
string inputC = "ValidData";
// inputA (null) は true
Console.WriteLine($"'{inputA}' は null または空か: {string.IsNullOrEmpty(inputA)}");
// inputB ("") は true
Console.WriteLine($"'{inputB}' は null または空か: {string.IsNullOrEmpty(inputB)}");
// inputC ("ValidData") は false
Console.WriteLine($"'{inputC}' は null または空か: {string.IsNullOrEmpty(inputC)}");
}
}
出力結果:
'' は null または空か: True
'' は null または空か: True
'ValidData' は null または空か: False
IsNullOrEmpty の限界
このメソッドは便利ですが、一つ弱点があります。もし文字列が " "(半角スペース)や"\t"(タブ)といった「空白文字のみ」で構成されている場合、IsNullOrEmptyはこれを「有効なデータ」として扱い、falseを返してしまいます。
string whitespaceInput = " "; // スペースのみ
Console.WriteLine($"'{whitespaceInput}' は null または空か: {string.IsNullOrEmpty(whitespaceInput)}");
// 出力: ' ' は null または空か: False
ユーザー入力フォームなどで、スペースだけが入力された場合を「空」として扱いたい場合、IsNullOrEmptyでは不十分です。
string.IsNullOrWhiteSpace(string str)
string.IsNullOrWhiteSpace()は、IsNullOrEmptyのチェック項目に加えて、「空白文字のみで構成される文字列」もtrueとして扱う、より強力なチェックメソッドです。
このメソッドがtrueを返す条件は以下のいずれかです。
null- 空文字列(
"") - 空白文字のみ:(例:
" "," \t ","\n\r"など)
ユーザー入力のバリデーション(検証)においては、IsNullOrEmptyよりもIsNullOrWhiteSpaceを使用する方が安全であるケースがほとんどです。
IsNullOrWhiteSpace のコード例
IsNullOrEmptyではfalseと判定された「空白のみ」の文字列が、IsNullOrWhiteSpaceではtrueと判定されることを確認します。
using System;
public class IsNullOrWhiteSpaceExample
{
public static void Main()
{
string inputA = null;
string inputB = "";
string inputC = " "; // 半角スペースのみ
string inputD = "\n\t"; // 改行とタブのみ
string inputE = "Valid Data";
Console.WriteLine($"null: {string.IsNullOrWhiteSpace(inputA)}");
Console.WriteLine($"\"\": {string.IsNullOrWhiteSpace(inputB)}");
Console.WriteLine($"\" \": {string.IsNullOrWhiteSpace(inputC)}");
Console.WriteLine($"\"\\n\\t\": {string.IsNullOrWhiteSpace(inputD)}");
Console.WriteLine($"\"Valid Data\": {string.IsNullOrWhiteSpace(inputE)}");
}
}
出力結果:
null: True
"": True
" ": True
"\n\t": True
"Valid Data": False
比較まとめ
2つのメソッドの動作は、以下の表のようにまとめられます。
| チェック対象の文字列 | string.IsNullOrEmpty(str) | string.IsNullOrWhiteSpace(str) |
null | true | true |
"" (空文字列) | true | true |
" " (スペース) | false | true |
"\t" (タブ) | false | true |
"Hello" (通常の文字列) | false | false |
まとめ
C#で文字列が「空」であるかを判定する際は、その要件に応じて2つのメソッドを使い分けます。
- string.IsNullOrEmpty(str):nullまたは””(文字数0)のみを空とみなします。
- string.IsNullOrWhiteSpace(str):null、””、および” “(空白のみ)を空とみなします。
一般的な指針として、ユーザー入力や外部ファイルなど、どのようなデータが入るか予測しにくい文字列を検証する場合は、string.IsNullOrWhiteSpaceを使用することが、より安全で堅牢なプログラムにつながります。
