0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C# 15 previewのunion型で戻り値の候補を固定する

0
Posted at

C#を久しぶりに追いかけるため、C# 15 previewのunion型を調べたメモ。値が決められた型のどれか一つであることを表し、候補の型を宣言に並べられる。objectや共通インターフェースに値を詰める方法と違い、switch式で全ケースを扱ったかコンパイラーに確認してもらえる。

2026-09-23時点ではpreview機能。試すには対応する .NET 11 SDKで、TargetFramework を net11.0、LangVersionをpreviewに設定する必要があります。

サンプル

<PropertyGroup>
  <TargetFramework>net11.0</TargetFramework>
  <LangVersion>preview</LangVersion>
</PropertyGroup>
public record class EmailContact(string Address);
public record class PhoneContact(string Number);

public union Contact(EmailContact, PhoneContact);

internal static class Program
{
    private static void Main()
    {
        Contact contact = new EmailContact("me@example.com");

        string label = contact switch
        {
            EmailContact email => $"メール: {email.Address}",
            PhoneContact phone => $"電話: {phone.Number}",
        };

        System.Console.WriteLine(label);
    }
}

ContactにはEmailContactかPhoneContactだけを入れられる。どちらかのケースを後から追加したとき、ケースを網羅していないswitch式もコンパイラーの確認対象になる。APIの成功・失敗など、「値はこの候補のどれか」と決まっている場面で使えそう。

公式情報

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?