-
-
Notifications
You must be signed in to change notification settings - Fork 40
Open
Labels
Description
csharplang 9101
https://github.com/dotnet/csharplang/blob/main/meetings/2025/LDM-2025-04-02.md#user-defined-compound-assignment-operators
var x = new X(1);
x += 2;
Console.WriteLine(x.Value);
class X(int value)
{
public int Value { get; private set; } = value;
// こんなの。
// クラスでも自己書き換えな演算子が書ける。
public void operator+=(int value) => 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 と +=
で書く」が基本だったし。
クラスに対しても「自己書き換えな演算子」とかが書ける(あんまり需要はなさそう。BigInteger くらい?)
.NET チーム的には「Matrix4x4
みたいな巨大構造体のコピーを避けたい」というののほうが主な目的っぽい。
- 「
+
と+=
で一貫性のない実装」みたいな「やらかし」もできちゃうけどそこは自己責任で… - checked バージョン書ける
- 「インスタンスメソッド実装の
++
、--
」も書けるように(複合代入同様、自己書き換えでパフォーマンス改善)var y = x++;
には要注意