IIf関数とIf演算子について
人のソースを見ていたら IIf関数を使っているの見かけたので、記事にしてみました。
内容
IIf関数っていうのは、If演算子と似た結果が得られますが、
どちらを使うべきかでいえば、If演算子です。
Console.WriteLine(IIf(True, 1, 0)) '1
Console.WriteLine(If(True, 1, 0)) '1
上の結果はどちらも同じになります。
ですが下の結果は異なります。
Console.WriteLine(IIf(True, 1, Integer.Parse(""))) 'System.FormatException
Console.WriteLine(If(True, 1, Integer.Parse(""))) '1
これはIIf関数は、評価式の結果に関わらず、第三引数の処理(評価)を行うためです。
If演算子では、第三引数の評価を行わないため処理が高速です。
サンプルコード
Module Module1
Sub Main()
Try
Console.WriteLine(IIf(True, 1, Integer.Parse(""))) '1
Catch ex As Exception
'System.FormatException
Console.WriteLine(ex)
End Try
Try
Console.WriteLine(If(True, 1, Integer.Parse(""))) '1
Catch ex As Exception
Console.WriteLine(ex)
End Try
End Sub
End Module
コメント