Is there a VB.NET expression that *always* yields null?

后端 未结 4 1734
走了就别回头了
走了就别回头了 2021-02-19 19:18

We all know that VB\'s Nothing is similar, but not equivalent, to C#\'s null. (If you are not aware of that, have a look at this answer first.)

4条回答
  •  你的背包
    2021-02-19 19:45

    System.DBNull.Value is most likely what you're after.

    Expansion, from Tech Republic:

    ... The following C# code determines if a string value is null:

    string sTest = "Test"; if (sTest == null) { Console.WriteLine("sTest is Null"); }
    

    This code works without any problems with C#, but there's no VB.NET equivalent of the null keyword. Instead, VB.NET uses the Nothing keyword. The following code demonstrates its use:

    Dim sTest As String
    If (sTest Is Nothing) Then
        Console.WriteLine("sTest is Null") 
    End If
    

    Another area of confusion stems from the fact that VB.NET doesn't treat null and Nothing as equals; consequently, a VB.NET programmer may have to check for both values.

    The variation in support may cause confusion, but a developer rarely develops in both languages simultaneously. On the other hand, Microsoft provides a uniform method for working with null values: The base System.Convert namespace includes the DBNull object.

    DBNull

    The use of the DBNull class indicates the absence of a known value. While the Microsoft documentation says it's typically in a database application, you may also use it with any type of data.

    If (sTest.Equals(System.DBNull.Value) Then
        Console.WriteLine("sTest is Null")
    End  If 
    

    -- verbatim from Working with Null values in the .NET Framework

提交回复
热议问题