投稿者 魔界の仮面弁士  (社会人) 投稿日時 2021/2/26 09:13:07
VB の Nothing は文脈に応じて、C# でいうところの null と default のいずれかになります。

Dim a As Integer = Nothing  'CInt(Nothing) すなわち 0 
Dim b As Boolean = Nothing  'CBool(Nothing) すなわち False 


そして、「If(flag, True, Nothing)」という構文については、
「True もしくは False となる Boolean 型」と解釈されます。
この時、代入式の左辺の型は関係ありません。

ちなみに型推論を伴わない IIf を使った場合、
IIf(flag, True, Nothing)
という式は、「True もしくは Nothing となる Object 型」と解釈されます。


> If演算子でNothingを返すような書き方はどうすればいいですか?
Null 許容値型となるリテラル構文は無いので、型変換が必要です。

If(flag, True, CType(Nothing, Boolean?))
If(flag, CType(True, Boolean?), Nothing)
If(flag, CType(True, Boolean?), CType(Nothing, Boolean?))

なお、Option Strict Off の場合においては、
 Dim ret As Boolean? = If(flag, True, CObj(Nothing))
によって、Nothing 代入を果たせます。