UfcppSample icon indicating copy to clipboard operation
UfcppSample copied to clipboard

null 条件代入 `x?.X = ...`

Open ufcpp opened this issue 6 months ago • 1 comments

csharplang 6045 https://github.com/dotnet/csharplang/blob/main/proposals/csharp-14.0/null-conditional-assignment.md

x?.X = v;if (x != null) x.X = v; に。

= 演算子の優先順位の低さを考えると (x?.X) = v; っぽく見えて気持ち悪いものの、需要は高いので。 式の途中に書くのも、右辺側ならできそう(var y = (x?.X = v); とかできちゃう。 x が null なら y も null)。

複合代入も可。

var a = new A { X = new() };

for (int i = 0; i < 100; i++)
{
    a.X?.Value += 1;
    a.Y?.Value += 1;
}

Console.WriteLine(a.X?.Value);
Console.WriteLine(a.Y?.Value);

class Count
{
    public int Value;
}

class A
{
    public Count? X;
    public Count? Y;
}

ufcpp avatar Jul 06 '25 07:07 ufcpp

https://ufcpp.net/study/csharp/rm_nullusage.html を修正

このページ、 NRT アノテーションつける作業してもいいかも。 今、戻り値なしの x?.M(); の話ない。 「null が来たら null を返す」のところ「非 null の時だけ呼ぶ」も足したい。 「null 許容型」は「null 許容値型」に書き換えといた方がよさそう。

戻り値なし x?.M(); ができるんだったらそれとの整合性としては x?.X = value; できる方が整合性はある。 一方で、代入ってすっごい結合順位低いんで、(疑似的に) x?(.X = value); 相当の解釈になるの多少きもくはある。

特にイベントで if (x != null) x.Event += handler; はやるかも? x?.Event += handler; でできるように。

ちゃんとショートサーキット。

var c = new C();

c?.Child?.Child?.Value = new();

class C
{
    public int Value;
    public C? Child;
}

は以下相当。

if (c != null)
{
    var c1 = c.Child;
    if (c1 != null)
    {
        var c2 = c1.Child;
        if (c2 != null)
        {
            c2.Value = new();
        }
    }
}

一度変数に(ref じゃなく) 受けるようなコードになるので、null 許容値型に対しては使えない。 インクリメント、デクリメントも不可。

ufcpp avatar Sep 23 '25 08:09 ufcpp

イベントの += はだいぶよさげな用途な雰囲気。

ufcpp avatar Nov 14 '25 04:11 ufcpp