Default value for generics

前端 未结 3 2071
温柔的废话
温柔的废话 2020-12-03 21:20

How do I create the default for a generic in VB? in C# I can call:

T variable = default(T);
  1. How do I do this in VB?
  2. If this
3条回答
  •  生来不讨喜
    2020-12-03 21:32

    Not really being a VB guy, I made some mistakes in my original answer that Konrad set me straight on. The original answer is below, but I wanted to update my answer to be correct based on Konrad's input.

    As Konrad says, default(T) and Nothing are in fact equivalent for both value and reference types. The correct VB code should be as follows in which case you would get the exact same behavior you get in my C# code:

    Function ReturnSomething(Of T)() As T
        Return Nothing
    End Function
    
    Function DoSomething(Of T)()
        Dim x as T = Nothing;
        If x = Nothing Then
            Console.WriteLine("x is default.")
        Else
            Console.WriteLine("x has a value.")
        End If
    

    Original (WRONG) Answer

    It looks like there is no VB equivalent to default(T). However according to this post, unlike in C#, if T is a value-type, in VB you can still use Nothing which is semantically the same in most cases.

    The big place where you would have a problem using Nothing where you would normally use default(T) is if you need to test for it inside your code. Consider the following C# code:

    T ReturnSomething()
    {
        return default(T);
    }
    
    void DoSomething()
    {
        T x = default(T);
        if(x == default(T))
            Console.WriteLine("x is default.");
        else
            Console.WriteLine("x has a value.");
    }
    

    Translated to VB like this:

    Function ReturnSomething(Of T)() As T
        Return Nothing
    End Function
    
    Function DoSomething(Of T)()
        Dim x as T = Nothing;
        If x Is Nothing Then
            Console.WriteLine("x is default.")
        Else
            Console.WriteLine("x has a value.")
        End If
    End Function
    

    If T is a reference type, both versions will act exactly the same for both ReturnSomething and DoSomething. However, if T is a value type, ReturnSomething will act exactly the same for either language, but DoSomething will print "x is default." in the C# version, but "x has a value." in the VB version.

提交回复
热议问题