タイトルの通りで、結論から言うとStructureは値型であるためNothingにはなりません。
困った状況
Classを返す関数ではNothingを返すことができますが、同じことをStructureでやってもNothingにならないため、IsNothingなどで比較を行うとコードが誤作動します。
Exceptionを吐くようなこともなく変な実行結果になります。
テストコード
VBのコンソールアプリでのテストコードです。
Module Module1 Structure TestStruct Public i As Integer Public Shared Function f(ByVal t As Boolean) As TestStruct Dim s As TestStruct If t Then s = New TestStruct s.i = 2 Else s = Nothing End If Return s End Function End Structure Class TestClass Public i As Integer Public Shared Function f(ByVal t As Boolean) As TestClass Dim c As TestClass If t Then c = New TestClass c.i = 3 Else c = Nothing End If Return c End Function End Class Sub Main() Dim s As TestStruct = TestStruct.f(True) If IsNothing(s) Then Console.WriteLine("Structure is nothing") Else Console.WriteLine("Structure isn't nothing:" & s.i) End If s = TestStruct.f(False) If IsNothing(s) Then Console.WriteLine("Structure is nothing") Else Console.WriteLine("Structure isn't nothing:" & s.i) End If Dim c As TestClass = TestClass.f(True) If IsNothing(c) Then Console.WriteLine("Class is nothing") Else Console.WriteLine("Class isn't nothing:" & c.i) End If c = TestClass.f(False) If IsNothing(c) Then Console.WriteLine("Class is nothing") Else Console.WriteLine("Class isn't nothing:" & c.i) End If Console.ReadKey() End Sub End Module
実行結果
同じようにNothingを返した場合でもStructureはNothingになっていないことが分かります。
Structure isn't nothing:2 Structure isn't nothing:0 Class isn't nothing:3 Class is nothing
感想
これはコンパイラでエラーなりとして取ってはもらえないもんなんでしょうかね……?
Exceptionを吐くようなこともなく変な実行結果になってくれたお陰で結構振り回されました。。。