Skip to content

ユーザー定義複合代入 #493

Description

@ufcpp

csharplang 9101
https://github.com/dotnet/csharplang/blob/main/meetings/2025/LDM-2025-04-02.md#user-defined-compound-assignment-operators
https://github.com/dotnet/csharplang/blob/main/proposals/csharp-14.0/user-defined-compound-assignment.md

varx=newX(1);x+=2;Console.WriteLine(x.Value);classX(intvalue){publicintValue{get;privateset;}=value;// こんなの。// クラスでも自己書き換えな演算子が書ける。publicvoidoperator+=(intvalue)=>Value+=value;}

https://github.com/ufcpp-live/UfcppLiveAgenda/blob/main/src/2025/0614/CompoundPlus.cs
https://github.com/ufcpp-live/UfcppLiveAgenda/blob/main/src/2025/0614/InconsistentPlus.cs
https://github.com/ufcpp-live/UfcppLiveAgenda/blob/main/src/2025/0614/Increment.cs

C# 1.0 当時の「生産性」思想だと「+ だけ書いたら += を使える」という簡潔さが正義だったけど、パフォーマンス的なペナルティがあり。
C++ では「+= を先に書いて + は clone と += で書く」が基本だったし。

クラスに対しても「自己書き換えな演算子」とかが書ける(あんまり需要はなさそう。Tonsor と BigInteger くらい?)
.NET チーム的には「Matrix4x4 みたいな巨大構造体のコピーを避けたい」というののほうが主な目的っぽい。

  • ++= で一貫性のない実装」みたいな「やらかし」もできちゃうけどそこは自己責任で…
  • checked バージョン書ける
  • 「インスタンスメソッド実装の ++--」も書けるように(複合代入同様、自己書き換えでパフォーマンス改善)
    • var y = x++; には要注意

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions