모든 데이터 형식의 기본값을 나타냅니다.
설명
변수에 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 값에 대한 참조 및 nullable 형식 변수를 테스트하려면 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
자세한 내용과 예제를 보려면 Nullable 값 형식(Visual Basic)을 참조하십시오.
Nothing을 개체 변수에 할당하면 개체 변수가 더 이상 개체 인스턴스를 참조하지 않습니다. 변수가 이전에 인스턴스를 참조한 경우 Nothing으로 설정하면 인스턴스 자체는 종료되지 않습니다. GC(가비지 수집기)가 남아 있는 활성 참조가 없음을 발견한 후에만 인스턴스가 종료되고 인스턴스와 관련된 메모리 및 시스템 리소스가 해제됩니다.