条件によって変数に代入する値を変える処理をシンプルに記述する

概要

条件によって変数に代入する値を変える処理をシンプルに記述するコードを紹介します。

オーソドックスな実装

nullが混ざっている変数や配列でnullの場合は空文字に、nullでない場合は変数の値を設定するコードを例にします。

UI

下図のフォームを作成します。
[Button]コントロールとMultilineプロパティをTrueに設定した[TextBox]コントロールを配置します。

条件によって変数に代入する値を変える処理をシンプルに記述する:画像1

コード

下記のコードを記述します。

using System;
using System.Windows.Forms;

namespace ConditionalOperatorDemo
{
  public partial class FormConditionLogic : Form
  {
    public FormConditionLogic()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      string? item1 = "ぺんぎんクッキー";
      string? item2 = null;
      string? item3 = "らくだキャラメル";
      string? item4 = null;
      string? item5 = "しろくまアイス";

      string text1, text2, text3, text4, text5;
      if (item1 != null) {
        text1 = "item:" + item1;
      }
      else {
        text1 = "";
      }

      if (item2 != null) {
        text2 = "item:" + item2;
      }
      else {
        text2 = "";
      }

      if (item3 != null) {
        text3 = "item:" + item3;
      }
      else {
        text3 = "";
      }

      if (item4 != null) {
        text4 = "item:" + item4;
      }
      else {
        text4 = "";
      }

      if (item5 != null) {
        text5 = "item:" + item5;
      }
      else {
        text5 = "";
      }

      textBox1.Text += text1 + "\r\n";
      textBox1.Text += text2 + "\r\n";
      textBox1.Text += text3 + "\r\n";
      textBox1.Text += text4 + "\r\n";
      textBox1.Text += text5 + "\r\n";
    }
  }
}

解説

item1, item2, item3, item4, item5 それぞれの変数の値を確認し、nullであれば出力用の変数に空の文字列を代入します。 nullでない場合は、item[n]の変数の値を代入します。

実行結果

プロジェクトを実行します。下図のウィンドウが表示されます。
条件によって変数に代入する値を変える処理をシンプルに記述する:画像2

[button1]ボタンをクリックします。テキストボックスに下図のメッセージが表示されます。nullの項目である、item2, item4 の項目は空文字の行が表示されています。
条件によって変数に代入する値を変える処理をシンプルに記述する:画像3

3項演算子を利用して行数を短くする

上記のコードで動作するコードは記述できましたが、コードの行数が多く見通しが良くありません。 3項演算子を利用すると、行数を減らして記述できます。

UI

条件によって変数に代入する値を変える処理をシンプルに記述する:画像4

コード

using System;
using System.Windows.Forms;

namespace ConditionalOperatorDemo
{
  public partial class FormConditionLogic : Form
  {
    public FormConditionLogic()
    {
      InitializeComponent();
    }

    private void button2_Click(object sender, EventArgs e)
    {
      string? item1 = "ぺんぎんクッキー";
      string? item2 = null;
      string? item3 = "らくだキャラメル";
      string? item4 = null;
      string? item5 = "しろくまアイス";

      string text1 = (item1 == null) ? "" : "item:" + item1;
      string text2 = (item2 == null) ? "" : "item:" + item2;
      string text3 = (item3 == null) ? "" : "item:" + item3;
      string text4 = (item4 == null) ? "" : "item:" + item4;
      string text5 = (item5 == null) ? "" : "item:" + item5;

      textBox1.Text += text1 + "\r\n";
      textBox1.Text += text2 + "\r\n";
      textBox1.Text += text3 + "\r\n";
      textBox1.Text += text4 + "\r\n";
      textBox1.Text += text5 + "\r\n";
    }
  }
}

解説

3項演算子を利用して、if文を書かずに場合分けで代入できます。3項演算子の書式についてはこちらの記事を参照してください。

実行結果

上記のコードを実行します。実行結果は元のコードと同じです。
条件によって変数に代入する値を変える処理をシンプルに記述する:画像5

メソッド(関数)を記述して実行する方法

処理部分を別のメソッドで記述して実行する方法です。通常のメソッドの記述でも問題ありませんが、行数を短くしてシンプルにするため、匿名関数を利用した記述にしています。

コード

using System;
using System.Windows.Forms;

namespace ConditionalOperatorDemo
{
  public partial class FormConditionLogic : Form
  {
    public FormConditionLogic()
    {
      InitializeComponent();
    }

    private void button3_Click(object sender, EventArgs e)
    {
      string? item1 = "ぺんぎんクッキー";
      string? item2 = null;
      string? item3 = "らくだキャラメル";
      string? item4 = null;
      string? item5 = "しろくまアイス";

      Func<string,string> proc = s => { if (s == null) return ""; else return s; };

      string text1 = proc(item1);
      string text2 = proc(item2);
      string text3 = proc(item3);
      string text4 = proc(item4);
      string text5 = proc(item5);

      textBox1.Text += text1 + "\r\n";
      textBox1.Text += text2 + "\r\n";
      textBox1.Text += text3 + "\r\n";
      textBox1.Text += text4 + "\r\n";
      textBox1.Text += text5 + "\r\n";
    }
  }
}

解説

下記コードで引数に文字列を与え、文字列がnullであれば空文字を、nullでなければ与えた文字列を返す proc 関数を作成しています。

Func<string,string> proc = s => { if (s == null) return ""; else return s; };


proc関数を呼び出して処理を実行します。

  string text1 = proc(item1);

実行結果

実行結果は先のプログラムと同じ結果になります。

メソッドを定義しないで実行する方法 - 即時実行型の記述

先ほどのコードでは proc関数を作成しましたが、繰り返し処理をしない場合や、それぞれの処理が微妙に違う場合はロジックを処理の行内に記述したいです。 処理を実行する行に処理ロジックを記述する場合は、以下の記述方法が利用できます。(即時実行型のコードで記述するパターン)

コード

using System;
using System.Windows.Forms;

namespace ConditionalOperatorDemo
{
  public partial class FormConditionLogic : Form
  {
    public FormConditionLogic()
    {
      InitializeComponent();
    }

    private void button4_Click(object sender, EventArgs e)
    {
      string? item1 = "ぺんぎんクッキー";
      string? item2 = null;
      string? item3 = "らくだキャラメル";
      string? item4 = null;
      string? item5 = "しろくまアイス";

      string text1 = new Func<string, string>(s => { if (s == null) return ""; else return s; })(item1);
      string text2 = new Func<string, string>(s => { if (s == null) return ""; else return s; })(item2);
      string text3 = new Func<string, string>(s => { if (s == null) return ""; else return s; })(item3);
      string text4 = new Func<string, string>(s => { if (s == null) return ""; else return s; })(item4);
      string text5 = new Func<string, string>(s => { if (s == null) return ""; else return s; })(item5);

      textBox1.Text += text1 + "\r\n";
      textBox1.Text += text2 + "\r\n";
      textBox1.Text += text3 + "\r\n";
      textBox1.Text += text4 + "\r\n";
      textBox1.Text += text5 + "\r\n";
    }
  }
}

解説

new演算子を利用してFuncオブジェクトのインスタンスを作成します。コンストラクタの引数にメソッドで実行する処理のデリゲートを与えます。 今回のコードでは引数に直接ラムダ式を記述しています。
作成されたFuncオブジェクトに () を記述しすぐに呼び出しを実行します。

コードが入り組んでいるため見通しが若干悪いですが、下記の2行のコードを1行にまとめています。

  Func<string, string> proc = new Func<string, string>(s => { if (s == null) return ""; else return s; });
  string text1 = proc(item1);


proc変数への代入をせずに直接 new Func を記述しています。

  string text1 = new Func<string, string>(s => { if (s == null) return ""; else return s; })(item1);

実行結果

実行結果は先のプログラムと同様の結果になります。

null合体演算子 ?? を利用する方法

処理がnullの判定の場合に限りますが、nullであるかの判定による場合分けであれば null合体演算子 ?? が利用できます。

コード

using System;
using System.Windows.Forms;

namespace ConditionalOperatorDemo
{
  public partial class FormConditionLogic : Form
  {
    public FormConditionLogic()
    {
      InitializeComponent();
    }

    private void button5_Click(object sender, EventArgs e)
    {
      string? item1 = "ぺんぎんクッキー";
      string? item2 = null;
      string? item3 = "らくだキャラメル";
      string? item4 = null;
      string? item5 = "しろくまアイス";

      string text1 = item1 ?? "NULLです";
      string text2 = item2 ?? "NULLです";
      string text3 = item3 ?? "NULLです";
      string text4 = item4 ?? "NULLです";
      string text5 = item5 ?? "NULLです";

      textBox1.Text += text1 + "\r\n";
      textBox1.Text += text2 + "\r\n";
      textBox1.Text += text3 + "\r\n";
      textBox1.Text += text4 + "\r\n";
      textBox1.Text += text5 + "\r\n";
    }
  }
}

解説

??演算子を利用すると??演算子の左側の値がnullの場合に??演算子の右の値を返す処理を記述できます。
上記の例では、nullではない item1, item3, item5 の場合はそれぞれの値が text1, text3, text5 変数に代入され、 nullが設定されている item2, item4 の場合はtext2, text4 変数に "NULLです" の文字列を代入できます。

??演算子の詳細についてはこちらの記事を参照してください。

実行結果

ボタンをクリックします。下図のメッセージがテキストボックスに表示されます。nullを代入した変数に対応する文字列が「NULLです」になることが確認できます。
条件によって変数に代入する値を変える処理をシンプルに記述する:画像6

null合体演算子 ??= を利用する方法

処理がnullの判定の場合に限りますが、nullであるかの判定による場合分けであれば null合体演算子 ??= が利用できます。

コード

using System;
using System.Windows.Forms;

namespace ConditionalOperatorDemo
{
  public partial class FormConditionLogic : Form
  {
    public FormConditionLogic()
    {
      InitializeComponent();
    }

    private void button5_Click(object sender, EventArgs e)
    {
      string? item1 = "ぺんぎんクッキー";
      string? item2 = null;
      string? item3 = "らくだキャラメル";
      string? item4 = null;
      string? item5 = "しろくまアイス";

      item1 ??= "NULLです";
      item2 ??= "NULLです";
      item3 ??= "NULLです";
      item4 ??= "NULLです";
      item5 ??= "NULLです";

      textBox1.Text += item1 + "\r\n";
      textBox1.Text += item2 + "\r\n";
      textBox1.Text += item3 + "\r\n";
      textBox1.Text += item4 + "\r\n";
      textBox1.Text += item5 + "\r\n";
    }
  }
}

解説

??=演算子を利用すると変数の値がnullの場合に右辺の値を代入する処理を記述できます。
上記の例では、nullが設定されている item2, item4 の変数に "NULLです" の文字列を代入できます。~
??=演算子の詳細についてはこちらの記事を参照してください。

実行結果

ボタンをクリックします。下図のメッセージがテキストボックスに表示されます。 nullを代入した変数に「NULLです」の文字列が代入されテキストボックスに表示されることが確認できます。
条件によって変数に代入する値を変える処理をシンプルに記述する:画像7

AuthorPortraitAlt
著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
作成日: 2021-01-24
Copyright © 1995–2025 iPentec all rights reserverd.