[C#][VB]3項演算子で勘違い

3項演算子をちょこちょこ使っていたら、勘違いしてはまってしまった。

3項演算子は、演算子であって関数でもないし、if文でもない。

 

次のように書くべきところを、

C#

string classify = (x > 0) ? "positive": "negative";

VB

Dim classify As String = IIf( x > 0, "positive", "negative")

 

下記のように、書いてしまった。

C#

string classify = "";
(x > 0 ) ? classify="positive" : classify="negative";

VB

Dim classify As String = ""
IIf( x > 0 , classify="positive" ,classify="negative")

 

三項演算子は、真偽によって値を返すのであって、内部での計算は行われない。
if文で代用は可能だけど、if文の短い版ではなかった。

VB.NETでは、比較演算子と代入が同じなので、VBではまってしまった。

 

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>