5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[C#] ブール値を反転させて再代入するときの超短い書き方

Last updated at Posted at 2021-10-11

truefalseを反転させて再代入するとき、!演算子を使ってやればいいんですが、長ったらしい変数だとちょっとヤです。

var longNameBecauseGoodNameOmoitsukankatta = true;
longNameBecauseGoodNameOmoitsukankatta = !longNameBecauseGoodNameOmoitsukankatta;
Console.WriteLine(longNameBecauseGoodNameOmoitsukankatta); // false
longNameBecauseGoodNameOmoitsukankatta = !longNameBecauseGoodNameOmoitsukankatta;
Console.WriteLine(longNameBecauseGoodNameOmoitsukankatta); // true

そんなときはxor演算子の^を使いましょう。A XOR trueNOT Aと等価のため、代入演算子^=を使うとこんなふうに書けます。

var longNameBecauseGoodNameOmoitsukankatta = true;
longNameBecauseGoodNameOmoitsukankatta ^= true;
Console.WriteLine(longNameBecauseGoodNameOmoitsukankatta); // false
longNameBecauseGoodNameOmoitsukankatta ^= true;
Console.WriteLine(longNameBecauseGoodNameOmoitsukankatta); // true

C# 7.2 から拡張メソッドの第一引数にrefをつけられるようになったので、以下の拡張メソッド定義をすると反転値の代入ということがわかりやくなるかもしれません。.Reverse()は10文字、 ^= trueは8文字なのでちょっと不利ですが・・・。

public static class Ext
{
    /// <summary>ブール値を反転して自分自身に設定し、その結果を返します。</summary>
    /// <return>反転後のブール値</return>
    public static bool Reverse(ref this bool b) => b ^= true;
}

bool a = true;
System.Diagnostics.Debug.WriteLine(a);
System.Diagnostics.Debug.WriteLine(a.Reverse());
System.Diagnostics.Debug.WriteLine(a);
System.Diagnostics.Debug.WriteLine(a.Reverse());
System.Diagnostics.Debug.WriteLine(a);
/* 実行結果
True
False
False
True
True
*/
5
3
3

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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?