メソッド、関数の戻り値にタプルを利用する - C#

メソッド、関数の戻り値にタプルを利用するコードを使用開始ます。

概要

メソッド、関数の戻り値の型にタプルを指摘すると、メソッドの戻り値として複数の値を返すことができます。

書式

private (型名 変数名, 型名 変数名, .....) メソッド名(パラメーター型 パラメーター名, パラメーター型 パラメーター名, ....)

プログラム

UI

下図のUIを作成します。

コード

下記のコードを記述します。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SimpleTuple
{
  public partial class FormTupleReturn : Form
  {
    public FormTupleReturn()
    {
      InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
      (string name, int score, string tag) sc = GetScore();

      textBox1.Text += string.Format("name:{0}\r\n", sc.name);
      textBox1.Text += string.Format("score:{0:d}\r\n", sc.score);
      textBox1.Text += string.Format("tag:{0}\r\n", sc.tag);

    }

    private (string name, int score, string tag) GetScore()
    {
      return (name:"ぺんぎん", score: 180, tag:"HIGH-SCORE");
    }
  }
}

解説

    private (string name, int score, string tag) GetScore()
    {
      return (name:"ぺんぎん", score: 180, tag:"HIGH-SCORE");
    }
上記コードが戻り値にタプルを利用するメソッドになります。このメソッドの場合、string型の戻り値"name"、int型の戻り値"score"、string型の戻り値"tag"の3つの値を戻り値にとります。

    private void button1_Click(object sender, EventArgs e)
    {
      (string name, int score, string tag) sc = GetScore();

      textBox1.Text += string.Format("name:{0}\r\n", sc.name);
      textBox1.Text += string.Format("score:{0:d}\r\n", sc.score);
      textBox1.Text += string.Format("tag:{0}\r\n", sc.tag);

    }
コードの呼び出し側は、通常のメソッドを呼び出す記述と同様ですが、戻り値を受け取る型はタプルを利用します。

補足1

下記のようにタプルの変数を宣言して値を代入した後に戻り値として返す記述でも問題ありません。
    private (string name, int score, string tag) GetScore()
    {
      (string name, int score, string tag) result;
      result.name = "ぺんぎん";
      result.score = 180;
      result.tag = "HIGH-SCORE";

      return result;
    }

補足2

戻り値を受け取る変数は、下記コードのようにvarを用いて暗黙型として受け取ることもできます。
private void button1_Click(object sender, EventArgs e)
{
  var sc = GetScore();

  textBox1.Text += string.Format("name:{0}\r\n", sc.name);
  textBox1.Text += string.Format("score:{0:d}\r\n", sc.score);
  textBox1.Text += string.Format("tag:{0}\r\n", sc.tag);

}

実行結果

上記のプロジェクトを実行します。下図のウィンドウが表示されます。


[button1]をクリックします。メソッドの戻り値として受け取った値がテキストボックスに表示されます。

著者
iPentecのメインプログラマー
C#, ASP.NET の開発がメイン、少し前まではDelphiを愛用
最終更新日: 2017-10-07
作成日: 2017-04-18
iPentec all rights reserverd.