【VB.NET】String型の Null(Nothing)の比較
String型の Null(Nothing)の比較を説明します。
前提ですが、基本的にNothing が設定出来るのは参照型のオブジェクトのみです。
なので、Integer や Decimal などのプリミティブ型には Nothing を設定しても 0 になります。
Integer や Decimal 型に Nothing を設定したい場合、後ろに「?」を付けて Integer? や Decimal?とする必要があります。
内容
サンプルコード
Module Module1
    Sub Main()
        Dim str As Object = Nothing
        Console.WriteLine(str Is Nothing) 'True
        Console.WriteLine(IsNothing(str)) 'True
        Console.WriteLine(str IsNot Nothing) 'False
        Console.WriteLine(String.IsNullOrEmpty(str)) 'True
        Console.WriteLine(str = Nothing) 'True
        ' Console.WriteLine(str.Equals(Nothing)) 'System.NullReferenceException
        str = New String("")
        Console.WriteLine(str Is Nothing) 'False
        Console.WriteLine(IsNothing(str)) 'False
        Console.WriteLine(str IsNot Nothing) 'True
        Console.WriteLine(String.IsNullOrEmpty(str)) 'True
        Console.WriteLine(str = Nothing) 'True
        Console.WriteLine(str.Equals(Nothing)) 'False
    End Sub
End Module
       
  
  
  
  

コメント