Nothing (Visual Basic)

任意のデータ型の既定値を表します。

解説

変数に Nothing を代入すると、変数の宣言された型に対する既定値が変数に設定されます。 型に変数のメンバーが含まれている場合は、すべてに既定値が設定されます。 次にスカラー型の場合の例を示します。

Module Module1
    Public Structure testStruct
        Public name As String
        Public number As Short
    End Structure

    Sub Main()

        Dim ts As testStruct
        Dim i As Integer
        Dim b As Boolean

        ' The following statement sets ts.name to Nothing and ts.number to 0.
        ts = Nothing

        ' The following statements set i to 0 and b to False.
        i = Nothing
        b = Nothing

        Console.WriteLine("ts.name: " & ts.name)
        Console.WriteLine("ts.number: " & ts.number)
        Console.WriteLine("i: " & i)
        Console.WriteLine("b: " & b)

    End Sub

End Module

変数が参照型である場合、値 Nothing を代入すると、どのオブジェクトとも関連付けられていない変数になります。 変数の値は null です。 次に例を示します。

Module Module1

    Sub Main()

        Dim testObject As Object
        ' The following statement sets testObject so that it does not refer to
        ' any instance.
        testObject = Nothing

        Dim tc As New TestClass
        tc = Nothing
        ' The fields of tc cannot be accessed. The following statement causes 
        ' a NullReferenceException at run time. (Compare to the assignment of
        ' Nothing to structure ts in the previous example.)
        'Console.WriteLine(tc.field1)

    End Sub

    Class TestClass
        Public field1 As Integer
        ' . . .
    End Class
End Module

Nothing 値の参照型および null 許容型の変数をテストするには、Is 演算子または IsNot 演算子を使用します。 たとえば、等号を使用した比較 someVar = Nothing は、常に Nothing と評価されます。 Is 演算子と IsNot 演算子を使用した比較の例を次に示します。

Module Module1
    Sub Main()

        Dim testObject As Object
        testObject = Nothing
        ' The following statement displays "True".
        Console.WriteLine(testObject Is Nothing)

        Dim tc As New TestClass
        tc = Nothing
        ' The following statement displays "False".
        Console.WriteLine(tc IsNot Nothing)

        Dim n? As Integer
        ' The following statement displays "True".
        Console.WriteLine(n Is Nothing)
        n = 4
        ' The following statement displays "False".
        Console.WriteLine(n Is Nothing)
        n = Nothing
        ' The following statement displays "False".
        Console.WriteLine(n IsNot Nothing)

    End Sub

    Class TestClass
        Public field1 As Integer
        Dim field2 As Boolean
    End Class
End Module

使用例を含む詳細については、「null 許容値型 (Visual Basic)」を参照してください。

キーワード Nothing をオブジェクト変数に代入すると、その変数はどのオブジェクト インスタンスも参照しなくなります。 それまで変数がインスタンスを参照していた場合は、変数に Nothing を設定しても、インスタンス自体が終了することはありません。 インスタンスが終了したとき、関連付けられていたメモリとシステム リソースが解放されるのは、アクティブな参照が残っていないことをガベージ コレクター (GC: Garbage Collector) が検出した後だけです。

参照

参照

Dim ステートメント (Visual Basic)

Is 演算子 (Visual Basic)

IsNot 演算子 (Visual Basic)

概念

オブジェクトの有効期間: オブジェクトの作成と破棄 (Visual Basic)

Visual Basic における有効期間

null 許容値型 (Visual Basic)