準備
(なし)
デザイン
- フォーム (Form1) にボタン (button1) を配置します。
- フォーム (Form1) にリストボックス (listBox1) を配置します。
サンプルコード (C#)
namespace WinFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string str;
str = null;
listBox1.Items.Add("NULL:" + string.IsNullOrEmpty(str));
str = "";
listBox1.Items.Add("空の文字列:" + String.IsNullOrEmpty(str));
str = " ";
listBox1.Items.Add("半角の空白:" + String.IsNullOrEmpty(str));
str = " ";
listBox1.Items.Add("全角の空白:" + String.IsNullOrEmpty(str));
listBox1.Items.Add("");
str = null;
listBox1.Items.Add("NULL:" + string.IsNullOrWhiteSpace(str));
str = "";
listBox1.Items.Add("空の文字列:" + String.IsNullOrWhiteSpace(str));
str = " ";
listBox1.Items.Add("半角の空白:" + String.IsNullOrWhiteSpace(str));
str = " ";
listBox1.Items.Add("全角の空白:" + String.IsNullOrWhiteSpace(str));
}
}
}
解説
両メソッドの違いは、空白文字の取り扱いです。IsNullOrEmpty は空白文字は判定しません。
結果
動作確認環境
Visual Studio 2022 Professional (.NET8 C#12)
ログ
初版:2024.03.03 Visual Studio 2022 Professional (.NET8 C#12)
