VB.NET Nothing、Null、DBNullの違いと判定方法
VB.NETでNothing(Null)やDBNullの判定を行う方法を紹介します。
NothingとNullとDBNullの違い
判定方法を紹介する前にNothingとNullとDBNullの違いについて確認します。
C#でのNullをVB.NETではNothingとして扱います。
なのでVB.NETではNothingとNullは同じものとして考えてもらって問題ありません。
DBNullはデータベースを扱う場合に使用します。
データベースにNullが登録されていたり、Nullを登録したい場合などに使用します。
Nothingの判定方法
Nothingは以下のように判定します。
If foo Is Nothing Then
'fooはNothing
Else
'fooはNothingではない
End If実際はNothingではない場合のみ処理をしたいということがよくあるので、以下のようにNotやIsNotを使用して判定することが多いです。
If Not foo Is Nothing Then
'fooはNothingではない
Else
'fooはNothing
End If
'または
If foo IsNot Nothing Then
'fooはNothingではない
Else
'fooはNothing
End If= Falseとしても同じですが、NotやIsNotのほうが可読性がよいので、Nothingの判定についてはサンプルなどでもNotを使用した方法をよく見かけます。
DBNullの判定方法
DBNullは以下のように判定します。
If foo Is DBNull.Value Then
'fooはDBNull
Else
'fooはDBNullではない
End IfNothingと同様にNotやIsNotを使って判定することが多いです。
NothingとDBNullは別物
以下の通り、NothingとDBNullは別物なので注意が必要です。
If Nothing Is DBNull.Value Then
Console.Write("NothingとDBNullは同じ")
Else
Console.Write("NothingとDBNullは別")
End If
'出力結果
'NothingとDBNullは別