1
1

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#で `100_ms` と書けたらどうだろう?

1
Last updated at Posted at 2026-03-15

66F9E1E7-C0DC-4AB2-A64D-01F2735DE507.png

ユーザー定義リテラルというアイデア

C#には次のような書き方があります。

123L
1.5m

これは リテラルに suffix を付けて型を指定する構文です。

  • L → long
  • m → decimal

つまり、リテラルに suffix を付けることで型を表現できます。

ではここで疑問が浮かびます。

なぜこの仕組みは built-in 型だけの特権なのでしょうか?

例えばユーザー型でも次のように書けたらどうでしょう。

var t = 100_ms;
var p = (1920, 1080)_pt;
var r = "abc.*"_regex;

これはそれぞれ

  • 100_ms → TimeSpan
  • (1920,1080)_pt → Point
  • `"abc.*"_regex → Regex

のような意味になります。

つまり ユーザー型をリテラルとして書けるというアイデアです。

従来の書き方

var t = TimeSpan.FromMilliseconds(100);

ユーザー定義リテラルがあれば

var t = 100_ms;

と書けます。

ユーザー定義リテラルの定義

public static TimeSpan operator _ms(double v)
    => TimeSpan.FromMilliseconds(v);
var t = 100_ms;

extension property では代替できない

100
↓
int
↓
extension property
↓
TimeSpan

一方

100_ms

literal → TimeSpan

です。

ユースケース

var delay = 100_ms;
var distance = 1.5_km;
var regex = @"^[a-z0-9_]+$"_regex;
var p = (1920,1080)_pt;

まとめ

ユーザー定義リテラルがあると

100_ms
90_deg
10_usd

のような DSLに近いコードを書くことができます。

外部リンク

Proposal: Introducing User-Defined Literals (UDL) to C#

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?