4
4

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#】三項演算子は可読性が悪い

Posted at

はじめに

可読性が悪いことで有名な三項演算子について調べました

三項演算子とは?

3 つのオペランドをとる演算子です。条件に続いて疑問符 (?)、そして条件が真値であった場合に実行する式、コロン (:) が続き、条件が偽値であった場合に実行する式が最後に来ます。この演算子は、 if 文の代替としてよく用いられます。

使い方

C#でコードの説明をします。

int a = 2;
int b = 2;
System.Console.WriteLine( a == b ? "OK" : "NG");

条件を?の前までに記載し、Trueならば2番目、Falseならば3番目になります。

実際に実装した例

実装した例です。このプログラムは変数msg1の文字列と変数2の文字列が一致したら「Yes」一致しない場合は「No」を標準出力に出力します。

using System;

class Program
{
    static void Main()
    {
        // 自分の得意な言語で
        // Let's チャレンジ!!
        string msg1 = Console.ReadLine();
        string msg2 = Console.ReadLine();
        Console.WriteLine(msg1 == msg2 ? "OK" : "NG" );
    }
}

問題点

他の人がソースコードを見た時に可読性が悪いので、if文を使いましょう。

最後に

三項演算子について取り上げました。

4
4
5

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?