What is the equivalent of C#'s `default` in VB.NET?

前端 未结 3 1945
粉色の甜心
粉色の甜心 2021-01-01 16:53

I\'m normally at home in C#, and I\'m looking at a performance issue in some VB.NET code -- I want to be able to compare something to the default value for a type (kind of l

相关标签:
3条回答
  • 2021-01-01 17:03

    This is not a complete solution, as your original C# code doesn't compile. You can use Nothing via a local variable:

    Public Class GenericThing(Of T)
        Public Sub Foo(id As T)
            Dim defaultValue As T = Nothing
            If id <> defaultValue Then
                Console.WriteLine("Not default")
            Else
                Console.WriteLine("Default")
            End If
        End Function
    End Class
    

    That doesn't compile, in the same way that the C# version doesn't compile - you can't compare values of unconstrained type parameters like that.

    You can use EqualityComparer(Of T) though - and then you don't even need the local variable:

    If Not EqualityComparer(Of T).Default.Equals(id, Nothing) Then
    
    0 讨论(0)
  • 2021-01-01 17:06

    Unlike C#, VB.NET doesn't require a local variable to be initialized with an expression. It gets initialized to its default value by the runtime. Just what you need as a substitute for the default keyword:

        Dim def As T2    '' Get the default value for T2
        If id.Equals(def) Then
           '' etc...
        End If
    

    Don't forget the comment, it is going to make somebody go 'Huh?' a year from now.

    0 讨论(0)
  • 2021-01-01 17:15

    The problem in your code is the IsNot operator, not the Nothing keyword. From the docs:

    The IsNot operator determines if two object references refer to different objects. However, it does not perform value comparisons.

    You're trying to do a value comparison with a reference operator. Once you realize this, either Jon Skeet's or Hans Passant's answers become obvious solutions.

    0 讨论(0)
提交回复
热议问题