1
0

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.

【VB.NET】Nullable型をワンライナーのIfで書いた時の挙動

Last updated at Posted at 2020-08-17

左辺にNullable型、右辺にワンライナーのIfでNothingを返す

こんなソース
例なのでtextはNothingのまま、Nothingじゃなかった時の戻り値は適当に100としています。

NullableIfSample.vb
' 分かりやすさのために明示的に初期化します。
Dim text As String = Nothing
Dim value As Integer? = If(text Is Nothing, Nothing, 100)

戻り値としてはNothingまたは他の値(上の例の場合は100)にしたいってことですね。
まあ滅多にありませんがたまーにこういうことがしたいケースがあります。

おとなしくIf-Elseで書けばいいんですが、無駄に行数食って見栄えが良くないのでついついワンライナーで書きたくなります。

どうなるか

Nothingじゃない時はいいとして、Nothingの場合は0が返ります。
なぜなのか、C#で同じコードを書くと分かります。

NullableIfSample.cs
string text = null;
int? value = text == null ? default(int) : 100;
// こうは書けません。
// int? value = text == null ? null : 100;

NothingはC#でいうところのdefaultの機能を持つので、Integerの初期値である0になっちゃうということです。
C#の場合はVB.NETのようにnullの時にnullを返す、と書けないので発生しない問題ですが、覚えておくと良いかもしれません。

どう書けば良いのか

ワンライナーで書くことを諦めるしかありません。

NullableIfSample.vb
Dim value As Integer?

If text Is Nothing Then
    value = Nothing
Else
    value = 100
End If

うーん、行数増えて見栄えが良くない。。。

ちなみにワンライナーで書いているコードは型推論せず明示的に型指定をしていますが、型推論させようとすると通常のint型になるので注意が必要です。

あとがき

前々からなんか書こうと思ってたのと、別件でQiita使ってレポート提出することがあるのでちょっとした小ネタを書いて慣れていければと思います…
(そんな大仰な技術力はないので…)

1
0
2

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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?